I want to play the gunshot sound once I click the left button mouse, but my code is not working.(is running without errors, but not playing the sound)
If I remove the "if condition" and run the game, once the game is running the the first thing will be the gunshot sound.
But if I use the "if condition" it does not work anymore even if I click the left mouse button. I need help to solve this one.
class Gun
{
Texture2D gun;
Vector2 position;
SoundEffect soundEffect;
public Gun(ContentManager Content)
{
gun = Content.Load<Texture2D>("Gun");
position = new Vector2(10, 10);
MouseState mouse = Mouse.GetState();
if (mouse.LeftButton == ButtonState.Pressed)
{
soundEffect = Content.Load<SoundEffect>("gunshot");
soundEffect.Play();
}
}
As mentioned in the comments on your original post, you are checking the LeftButton state only when the object is created. What you need to do is add an Update method that does the check and plays the sound effect. I would also move the soundEffect loading out of that loop and do it when you construct or load the object so you have something like this:
public class Gun
{
Texture2D gun;
Vector2 position;
SoundEffect soundEffect;
MouseState _previousMouseState, currentMouseState;
public Gun(ContentManager Content)
{
gun = Content.Load<Texture2D>("Gun");
soundEffect = Content.Load<SoundEffect>("gunshot");
position = new Vector2(10, 10);
}
public void Update(GameTime gameTime)
{
// Keep track of the previous state to only play the effect on new clicks and not when the button is held down
_previousMouseState = _currentMouseState;
_currentMouseState = Mouse.GetState();
if(_currentMouseState.LeftButton == ButtonState.Pressed && _previousMouseState.LeftButton != ButtonState.Pressed)
soundEffect.Play();
}
}
Then in your Game's Update loop, just call gun.Update(gameTime) (where gun is an instance of your gun class)
Related
I'm creating a Character Selection Menu for my mobile game. I have a GlobalManager Gamobject which is a singelton persisting through scenes. Then I have a GameSession Gameobject which controls stuff inside the Gameplay Scene.
In MenuScene inside character selection window when I click on the character toggle I call function, which sets sprite and runtimeAnimatorController into a field of GlobalManager. Then When I load the Gameplay inside Start I call the function below to set the Player sprite and Animator.
Problem is that the Animator is set but the sprite not. Also when I start moving the player it looks like the Animator is calling all Animations at once for 3-4 sec until it stabilizes and starts playing the right one.
#region Set Character
public void SetCharacter(GameObject player)
{
if (CharacterSprite && CharacterRuntimeAnimatorController && player)
{
player.GetComponent<SpriteRenderer>().sprite = CharacterSprite;
if (player.GetComponent<PlayerBehavior>() && player.GetComponent<Animator>())
{
player.GetComponent<Animator>().runtimeAnimatorController = CharacterRuntimeAnimatorController;
}
}
}
#endregion
Expected behavior is that the sprite will be set and the Animator won't be glitching
EDIT:
When I deactivate Animator on Player GameObject the sprite is set. Still not sure what is causing this problem
EDIT 2:
Following script enables the sprite to be set but the Animation glitch remains
public void SetCharacter(GameObject player)
{
if (CharacterSprite && CharacterRuntimeAnimatorController && player)
{
player.GetComponent<SpriteRenderer>().sprite = CharacterSprite;
if (player.GetComponent<PlayerBehavior>() && !player.GetComponent<Animator>())
{
player.AddComponent(typeof(Animator));
}
if (player.GetComponent<PlayerBehavior>() && player.GetComponent<Animator>())
{
player.GetComponent<Animator>().runtimeAnimatorController = CharacterRuntimeAnimatorController;
}
}
}
using UnityEngine;
public class PlayerLoad : MonoBehaviour
{
[SerializeField]
private Sprite pSprite;
private void Start()
{
LoadSprite(this.gameObject, pSprite);
}
void LoadSprite(GameObject p1, Sprite pSprite = null) // p1 = the player's gameobject
{
var sr = p1.GetComponent<SpriteRenderer>();
if (sr == null)// If no sprite renderer exist
{
sr = p1.AddComponent<SpriteRenderer>();
}
if (sr != null && !sr.enabled)// If sprite renderer exist but isn't active
{
sr.enabled = true;
}
if (sr.sprite == null)// If no sprite exist, adds one
{
p1.GetComponent<SpriteRenderer>().sprite = pSprite;
}
}
}
Ok, so I'm having an issue to where sometimes my player's sprite seems to be invisible. As of now, I can build the project onto my mobile device and everything works fine. However, when the second level is completed (Right now I only have two levels I'm using for testing) the game goes to the Death scene. Then it ask's the user to continue or quit. If continue, the player is taken to the last level reached. Code works, but the sprite is now invisible. Sometimes I can pause the game, quit and return to the main menu, click play again and start over and the player appears again. Other times it makes it worse because the bullets even fail to render. I have no clue as to what could cause such a thing. SO I have this code in hopes of forcing the sprite to render whether it wants to or not.
Here's a screenshot of the mobile screen:
To the right you can see the bullets firing but the player cannot be seen. You can tell the player is moving by the offset in the bullet trajectory. (If you look close)
I'm using Unity 2019.0.1a Beta
I am new in Game Programming but I'm interested in this domain; now I am working on a small game for my course work. I have used some ideas from the internet to make my hero jump; the code is working, but after I press first time space, the hero is jumping and is not coming back to his position, he remains on the top of the screen. Please help me to make my hero, then return to his initial position. If I press space again he is jumping, but is jumping there, on the top of the screen.
public void Initialize()
{
startY = position.Y;
jumping = false;
jumpspeed = 0;
}
public void Update(GameTime gameTime)
{
KeyboardState keyState = Keyboard.GetState();
rectangle = new Rectangle(currentFrame * frameWidth, 0, frameWidth, frameHeight);
origin = new Vector2(rectangle.Width / 2, rectangle.Height / 2);
AnimateRight(gameTime);//calling AnimateRight function to animate heroes sprite
if (jumping)
{
position.Y += jumpspeed;
jumpspeed += 1;
if (position.Y >= startY)
{
position.Y = startY;
jumping = false;
}
}
else
{
if (keyState.IsKeyDown(Keys.Space))
{
jumping = true;
jumpspeed = -14;
}
}
}
You have to set startY when pressing Space:
if (keyState.IsKeyDown(Keys.Space))
{
jumping = true;
jumpspeed = -14;
startY = position.Y;
}
I know that you are new, but I replicated a movement system that worked great if you can understand it, here is the link to see the player movement in action, and here is the web site for it. If you want to download it here is the link.
This player movement uses a couple important things,
First:
Inside the Player class there is a method called public Player, yes, you make a method that is the same name as the class. By doing this you can transfer information from the Game1 class to Player class. So you can send the player texture, position, speed, ect...
Second:
Inside the Player method the info that is called over from the Game1 class needs to be collected and stored in the Player class. So if you wanted to transfer the texture of you player you would need to do the following.
Create the Player Texture and create a the link that will allow you to create the link to the Player class:
Texture2D personTexture;
'Player player'
Then in the Load Content you need to call on the personTexture and put it into the player function:
personTexture = Content.Load <Texture2D>("Person");
player = new Player(personTexture);
Now that the Texture is now in side the Player method in the Player class you will now store it in the Player class so that you can use it, add a Texture2D Texture to your Player class then enter the following:
public Player(Texture2D Texture)
{
this.Texture = Texture;//this.Texture is the one you create in side the
Player class, the other is the Texture you stated
}
Now your done and able to use your texture in that class.
Hopefully this will help you understand how to create your jumping player.
I am a newbie in game development, and I am developing a concept for windows store using monogame implementation of XNA where in, I am making a ball move on flick gesture. But, my problem is the ball moves not only on applying the gesture on to the ball but applying the gesture anywhere on the screen makes my ball move. What I want is, my ball shall only move when I apply flick on the ball itself but not on the other areas of the screen. I am using rectangle bounding box to see whether user touches the ball object but in vain.
I am sharing with my method to Update Gametime
//Global vars
//cat is the ball object here
GraphicsDeviceManager _graphics;
SpriteBatch _spriteBatch;
private Texture2D cat;
private Vector2 _spritePosition;
private SpriteFont _fontMiramonte;
BounceableImage mBall;
const float DECELERATION = 1000;
Vector2 position = Vector2.Zero;
Vector2 velocity;
//Update method
protected override void Update(GameTime gameTime)
{
// TODO: Add your update logic here
while (TouchPanel.IsGestureAvailable)
{
GestureSample gesture = TouchPanel.ReadGesture();
if (IsPointInObject(position))
{
if (gesture.GestureType == GestureType.Flick)
velocity += gesture.Delta;
if (gesture.GestureType == GestureType.Hold)
position = gesture.Position;
}
}
// Use velocity to adjust position and decelerate
if (velocity != Vector2.Zero)
{
float elapsedSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
position += velocity * elapsedSeconds;
float newMagnitude = velocity.Length() - DECELERATION * elapsedSeconds;
velocity.Normalize();
velocity *= Math.Max(0, newMagnitude);
}
UpdateSprite(gameTime, ref position, ref velocity);
base.Update(gameTime);
}
//method to detect whether the touched point lies inside the object ball
public bool IsPointInObject(Vector2 positionVector)
{
Rectangle bbx = new Rectangle((int)position.X , (int)position.Y, (int)cat.Width, (int)cat.Height);
return bbx.Contains((int)(positionVector.X), (int)(positionVector.Y));
}
You'll have to set a canvas on TouchPanel and set and lock this canvas for gesture movements from player. You'll have to set canvas block smaller from Panel, where you want to see touch effect.
I am trying to update my player by mouse click. I have tried different actions on player to update such as free drag. They work. But mouse click does not work. Can anybody help me?
For more detail, my player class holds animation texture and its position. I am trying to change another texture to current one.
It works. I mean: when I drag the player its animation changes. It means my class functionality has no problem. But when I try the same thing with mouse click, it does not work.
//initialize method
player.Initialize(player1, player1.Position);
//update method
protected override void Update(GameTime gameTime)
{
currentMouseState = Mouse.GetState();
UpdatePlayer(gameTime);
_bgLayer1.Update(gameTime);
_bgLayer2.Update(gameTime);
base.Update(gameTime);
}
//update player method
void UpdatePlayer(GameTime gameTime)
{
player.Update(gameTime);
// Touch inputs
while (TouchPanel.IsGestureAvailable)
{
GestureSample gesture = TouchPanel.ReadGesture();
if (gesture.GestureType == GestureType.FreeDrag)
player.Position += gesture.Delta;
player.PlayerAnimation = player2;
}
// Get Mouse State
if (previousMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
player.PlayerAnimation = player2;
}
previousMouseState = currentMouseState;
}