shoot on keypress in 2D game with XNA game studio - c#

I'm developing a 2D game with XNA game studio 4.0 and I need to make my "Hero" sprite shoot a shot sprite, which is a rectangle.
When I press left control to shoot, the shot is starting from my player. So far, it's ok, but the problem is that it never stops - its position never goes to theVoid.
Here is my code for shooting:
protected override void Update(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.LeftControl) && isShotted == false)
{
isShotted = true;
shotPosition = playerPosition;
}
if (isShotted == true && (shotPosition.X <= shotPosition.X+150) )
{
shotPosition.X += shotSpeed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
}
else
{
isShotted = false;
shotPosition = theVoid;
}
}
Some clarification:
playerPosition is my "Hero" sprite position.
theVoid is Vector2 (700,700), when I set shotPosition = theVoid the shot dissapears.

The shot never disapears because you are updating shotPosition.x every update. You are checking:
if (isShotted == true && (shotPosition.X <= shotPosition.X+150) )
And then inside that if you increment shotPosition.X:
shotPosition.X += shotSpeed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
One option to fix this would be to check shotPosition.X against the player position - per #jonhopkins comment. If the player can move near the same speed as the shot though, they could just follow it and then the shot would never disappear, this may or may not be what you want.
Your other option is to store the position of where the shot was fired, and compare something like:
if (isShotted == true && (shotPosition.initialX+150 >= shotPosition.currentX) )
Make sure you think about this in terms of how your players and objects move around the coordinate system though. If your player is always stationary in regards to the x-axis that could simplify things compared to if they can run around the screen..

Related

Zoom in / out in OpenGL C#

I'm trying to create a OpenGL C# project to zoom in and out for a scene. I want to enter and exit fom zoom mode when I press the Z key. And then, when I'm in zoom mode ( Z key pressed first time ) to use the mouse wheel to zoom in / out the scene. When I finished the zoom action, I want to be able to exit the zoom mode ( press Z again ) and then the mouse wheel will stop zooming my scene. Thanks for help!
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
Matrix4 lookat = Matrix4.LookAt(eyeVector, targetVector, upVector);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadMatrix(ref lookat);
KeyboardState keyboard = Keyboard.GetState();
if (keyboard[Key.Z] && !keyboard.Equals(lastKeyPress))
{
}
if (keyboard[Key.Z] && !keyboard.Equals(lastKeyPress))
{
}
lastKeyPress = keyboard;
}
This is the function for zoomOut:
public Vector3 zoomOut(Vector3 actual)
{
if(zoomLimits[1]<=actual.X || zoomLimits[1] <= actual.Y || zoomLimits[1] <= actual.Z) {
Console.WriteLine("Limita de zoomOut a fost atinsa!");
return actual;
}
Vector3 nou = new Vector3(actual.X + 5, actual.Y + 5, actual.Z + 5);
return nou;
}
Here I just change the eyeVector from the lookat matrix. But I have some limits. If I exceed those limits the scene will dissapear. Do you have any ideas to solve this? I dont want limits for zoom.
There's only so much help I can give without seeing your full code, but have you checked the clipping planes? That sounds like a textbook case of having a clipping plane too close; check your perspective matrix.
When you call Matrix4.CreatePerspectiveFieldOfView, increase depthFar, that should fix your issue.

Collision on X axis means 0 movement in Y axis

I'm developing a platformer in Unity using the 2D engine. I have my player character which has a BoxCollider2D and a RigidBody, and a number of 'walls' which have BoxColliders.
Now, I copied the script for moving the player from another project and made some changes. The part which has to do with movement is as follows:
public void FixedUpdate()
{
physVel = Vector2.zero;
// move left
if(Input.GetKey(KeyCode.LeftArrow))
{
physVel.x = -runVel;
}
// move right
if(Input.GetKey(KeyCode.RightArrow))
{
physVel.x = runVel;
}
// jump
if(Input.GetKey(KeyCode.UpArrow))
{
if(jumps < maxJumps)
{
jumps += 1;
if(jumps == 1)
{
_rigidbody.velocity = new Vector2(physVel.x, jumpVel);
}
}
}
//Apply gravity
_rigidbody.AddForce(-Vector3.up * fallVel);
// actually move the player
_rigidbody.velocity = new Vector2(physVel.x, _rigidbody.velocity.y);
}
Now this works perfectly fine.
The problem arises if the player jumps into a wall. If I keep the direction button mashed 'towards' the wall after having jumped, he is suspended in mid-air. As in the collision appears to be reducing movement on both axis to zero. If I release the direction, he falls normally. Collisions on the other axis works fine. I can hit my head or walk without issue.
Am I missing something obvious?
EDIT: try adding a material with 0 friction to both player and walls and see what happens, if it stops it is a friction error.

Move Sprite gradually up (Jump)

Im having a problem making a sprite Jump on my XNA Game for Windows Phone when I touch the screen.
I have the following code at the moment.
foreach (TouchLocation tl in touchCollection)
{
if ((tl.State == TouchLocationState.Pressed))
{
rectangleSprite.Y -= 55;
}
}
NOTE:
rectangleSprite = new Rectangle((int)newPosition.X, (int)newPosition.Y, textureSprite.Width, textureSprite.Height)
MY code makes the sprite move to the new position. That works as a jump, but I want it to be more gradually, so you can see it jumping.
To make your character jump better you have to add velocity to your code, and put your jump function in the update() method.
You need to add gravity.
In your update you can add something like this.
float i = 1; velocity.Y += 0.15f * i;
Reminder: ^this only works if you set your code so, that you character can't go below the surface it stands on.
Because it will make it go down every time the code calls the update() method.
Then if you want, make a boolean, to check if you player has jumped.
foreach (TouchLocation tl in touchCollection)
{
if ((tl.State == TouchLocationState.Pressed && hasJumped == false))
{
position.Y -=10f;
veloctity.Y -= 5f;
}
}
EDIT:
Do not forget to update the position of your character.
The position:
Vector2 position;
the update code:
position = position + velocity;
Some things u might want to read/watch:
Like scheien said:
http://www.xnadevelopment.com/tutorials/thewizardjumping/thewizardjumping.shtml
Little video that maybe helps with explaining.
http://www.youtube.com/watch?v=ZLxIShw-7ac
I'm also on this site to learn so any suggestions or edits are welcome!

Tile Engine Collision

Okay, so, I am making a small tile-based digging game, now I want to do collision. How would I go about doing this correctly? I know how to check if the player collides with a tile, but I don't know how to actually make the player stop when it hits a wall.
This is the game, I got 20x20 tiles here.
This is the code I'm using atm:
foreach (Tile tiles in allTiles)
{
if (ply.rect.Intersects(tiles.rect))
{
if (tiles.ID != -1 && tiles.ID != 1)
{
if (ply.X > tiles.X)
{
Console.WriteLine("Right part.");
ply.X = tiles.pos.X + 30;
}
if (ply.X <= tiles.X)
{
Console.WriteLine("Left part.");
ply.X = tiles.pos.X - 30;
}
if (ply.Y > tiles.Y)
{
Console.WriteLine("Bottom part.");
ply.Y = tiles.pos.Y + 30;
}
if (ply.Y <= tiles.Y)
{
Console.WriteLine("Upper part.");
ply.Y = tiles.pos.Y - 30;
}
}
}
}
What type of collision detection are you using?
If your using Rectangles and the '.intersects' method you can always declare a bool to make sure your character is touching the floor. If he isn't you apply a Gravity Vector to make it fall to the next Tile with a different Rectangle so when he hits it he's going to stop falling.
If you want to block him from side to side just test to see which side of the rectangle he is touching and block him from moving on the 'X' axis.
E.g if he is going right and intersects with the left part of a rectangle, block is 'GoingRight' movement.
if(myCharacterRectangle.Intersects(tileRectangle)
{
if(myCharacterPosition.X > (tilePosition.X)
{
//You know the character hits the Right part of the tile.
}
if(mycharacterPosition.X <= tilePosition.X)
{
//You know the character hits the Left Part of the tile.
}
}
And same goes for the Position.Y if you want to test the Top or Bottom.
If you want to use Pixel by Pixel collision detection using Matrices I know a good tutorial here.
The detection will return a 'Vector2(-1,-1)' if there is no collision.
If there is a one the method will return the coordinates of the collisions which makes it even easier to determine what part of the tile your character is touching.
Hope this helps. Good Luck with your game.

problem designating a bound for my sprite in XNA

i just got into game development and XNA and was following a tutorial and decided to try and add in a bound area for a floor. In the tutorial the sprite could move freely and i wanted to have a stopping point for it, so i added a statement to part of the input method
if (aCurrentKeyboardState.IsKeyDown(Keys.Down) == true)
{
if (this.Position.Y == 420)
{
MOVE_DOWN = 0;
mDirection.Y = MOVE_DOWN;
}
else
{
mSpeed.Y = PLAYER_SPEED;
MOVE_DOWN = 1;
mDirection.Y = MOVE_DOWN;
}
}
MOVE_DOWN is my variable for the y change, if it = 0, there is no movement, 1 it moves down, -1 it moves up.
this worked only if the position of the bounds(420) was equal to the position that my sprite started out at, other than that it doesnt work.
i think its because the position isnt updating correctly. i dont know ive tried a lot of things and am pretty new with XNA and game development. Any help would be greatly appreciated.
Here is the update method for my player sprite
public void Update(GameTime theGameTime)
{
KeyboardState aCurrentKeyboardState = Keyboard.GetState();
UpdateMovement(aCurrentKeyboardState);
mPreviousKeyboardState = aCurrentKeyboardState;
base.Update(theGameTime, mSpeed, mDirection);
}
and here is the update for the base class
public void Update(GameTime theGameTime, Vector2 theSpeed, Vector2 theDirection)
{
Position += theDirection * theSpeed * (float)theGameTime.ElapsedGameTime.TotalSeconds;
}
If 'Position' is a Vector2, then it is using floats of the X & Y components.
For practical purposes, a float will rarely equal a whole number due to floating point rounding errors.
if (this.Position.Y == 420)//will never return true
should be changed to:
if (this.Position.Y < 420)
{
this.Position = 420;
//other stuff you have
}

Categories

Resources