Character jump in XNA - c#

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.

Related

How can I restrict gameobject from moving beyond line in unity

I have this red apple that needs to move only inside the green apple line. If it tries to move beyond line it will be stopped at the green line and can' move beyond. How can I do that?
This is the code I use to move a red apple.
Camera mainCamera;
float zAxis = 0;
Vector3 clickOffset = Vector3.zero;
// Use this for initialization
void Start()
{
mainCamera = Camera.main;
mainCamera.gameObject.AddComponent<Physics2DRaycaster>();
zAxis = transform.position.z;
}
public void OnBeginDrag(PointerEventData eventData)
{
clickOffset = transform.position - mainCamera.ScreenToWorldPoint(new Vector3(eventData.position.x, eventData.position.y, zAxis));
}
public void OnDrag(PointerEventData eventData)
{
//Use Offset To Prevent Sprite from Jumping to where the finger is
Vector3 tempVec = mainCamera.ScreenToWorldPoint(eventData.position) + clickOffset;
tempVec.z = zAxis; //Make sure that the z zxis never change
/*
Debug.Log(tempVec.x);
if (tempVec.x < 90)
{
tempVec.x = 90;
}
if (tempVec.x > 310)
{
tempVec.x = 310;
}
*/
transform.position = tempVec;
}
public void OnEndDrag(PointerEventData eventData)
{
}
Don't use code for this use colliders on both sides.
I recommend to use the polygon collider with this (although it's a bit buggy). Then when you're dragging the apple you don't set the position but you set the velocity based on the difference between the mouse and the apple.
Unfortunately, high-velocity objects are not always resolved properly in Unity. In the case that unity doesn't always resolve the collision properly I recommend raycasting the difference from the apple to the cursor, if you get a hit instead of using the cursor position you can now use the hit position.
NOTE: Make sure it's not normalized because you want the velocity to be more if the cursor is further away from the fruit.
You could add a mesh renderer onto the big green apple. Then in your script you can check for collision and make the small apple react to the collision the way you'd like.

Particle system rendering behind another GameObject

First, I want you to understand my English.
I manually change the camera's projection to orthographic using the source code.
Please refer to the code below.
using UnityEngine;
using System.Collections;
public class CameraOrthoController : MonoBehaviour
{
private Matrix4x4 ortho;
private Matrix4x4 perspective;
public float near = 0.001f;
public float far = 1000f;
private float aspect;
public static CameraOrthoController Instance
{
get
{
return instance;
}
set { }
}
//-----------------------------------------------------
private static CameraOrthoController instance = null;
//---------------------------------------------------
// Use this for initialization
void Awake()
{
if (instance)
{
DestroyImmediate(gameObject);
return;
}
// 이 인스턴스를 유효한 유일 오브젝트로 만든다
instance = this;
}
private void Start()
{
perspective = Camera.main.projectionMatrix;
}
public void StartMatrixBlender(float OrthoSize)
{
aspect = (Screen.width + 0.0f) / (Screen.height + 0.0f);
if (OrthoSize != 0f)
{
float vertical = OrthoSize;
float horizontal = (vertical * 16f) / 9f;
ortho = Matrix4x4.Ortho(-horizontal, horizontal, -vertical, vertical, near, far);
BlendToMatrix(ortho, 1f);
}
else
{
BlendToMatrix(perspective, 1f);
}
}
//---------------------------------------
private Matrix4x4 MatrixLerp(Matrix4x4 from, Matrix4x4 to, float time)
{
Matrix4x4 ret = new Matrix4x4();
int i;
for (i = 0; i < 16; i++)
ret[i] = Mathf.Lerp(from[i], to[i], time);
return ret;
}
IEnumerator LerpFromTo(Matrix4x4 src, Matrix4x4 dest, float duration)
{
float startTime = Time.time;
while (Time.time - startTime < duration)
{
Camera.main.projectionMatrix = MatrixLerp(src, dest, (Time.time - startTime) / duration);
yield return new WaitForSeconds(0f);
}
Camera.main.projectionMatrix = dest;
}
//-------------------------------------------------
private Coroutine BlendToMatrix(Matrix4x4 targetMatrix, float duration)
{
StopAllCoroutines();
return StartCoroutine(LerpFromTo(Camera.main.projectionMatrix, targetMatrix, duration));
}
//-------------------------------------------------
public void OnEvent(EVENT_TYPE Event_Type, Component Sender, object Param = null, object Param2 = null)
{
switch (Event_Type)
{
}
}
}
I use code this way.
CameraOrthoController.Instance.StartMatrixBlender(OrthographicSize);
This has worked well so far.
However, the problem occurred when i added particle system for effect.
The screen where the problem is occurring
In a normal state, the effect appears in front of the gameobject, as shown on the scene screen at the bottom of the picture above.
But if I use the code I wrote above to manipulate the camera, the effect will always be obscured by all gameobject, as if it were on the game screen at the top of the picture. Despite the fact that the effects are located in front of the game object.
At first, I thought it would be possible to solve it with layer sorting, but I don't think it's a layer problem because it's visible under normal camera conditions.
I want to know where the problem is with the above codes because I have to use them.
Please let me know if you know how to solve it.
Thank you.
When you modify Camera.projectionMatrix, the camera will no longer update its rendering based on the field of view. The particle will remain behind the GameObject until you call Camera.ResetProjectionMatrix() which ends the effect off setting the Camera.projectionMatrix property.
If this doesn't work, use multiple cameras to make the particle system always appear on top of the 3D object. Basically, you render the 3D Object and other objects with the main camera then render the Particle System with another camera.
Layer:
1.Create new layer and name it "Particle"
2.Change the Particle System layer to Particle
Main Camera:
1.Make sure that the main camera's Clear Flags is set to Skybox.
2.Change the Culling Mask to "Everything". Click on Everything which is a setting of Culling Mask and de-select/uncheck Particle.
3.Make sure that its Depth is set to 0.
The camera should not render the Particle System at this point.
New Camera:
1.Create new Camera. Make sure it's at the-same position/rotation as the main camera. Also remove the AudioListener that is attached to it.
2.Change Clear Flags to Depth only.
3.Change the Culling Mask of the camera to be Particle and make sure that nothing else is selected in the "Culling Mask"
4.Change Depth to 1.
This will make the Particle System to always display on top of every object rendered with the first or main camera.
If you want the Particle System to appear on top of a Sprite/2d Object instead of Mesh/3D Object, change the sortingOrder of the particle's Renderer to be bigger than the SpriteRenderer's sortingOrder. The default is 0 so changing the Particle's sortingOrder to 1 or 2 should be fine.
particle.GetComponent<Renderer>().sortingOrder = 2;

Apply gesture effects only when the user touches the object

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.

XNA 3.1 - Not sure how to add Rectangle in enemy Class

Trying to make a 2D side scroller here
I am quite new to programming. I've tried to follow guides and tutorials with not much luck. I am aware that this is quite simple but i just cannot figure it out.
I have multiple classes for all the different characters in the game.
I have a rectangle for the main sprite character which the player will control.
But the problem is that I want to add rectangles around enemy sprites so that i can add collision into the game.
public class enemyRocks
{
public Texture2D texture;
public Vector2 position;
public Vector2 velocity;
public Rectangle rockRectangle;
public bool isVisible = true;
Random random = new Random();
int randX;
public enemyRocks(Texture2D newTexture, Vector2 newPosition)
{
texture = newTexture;
position = newPosition;
randX = -5;
velocity = new Vector2(randX, 0);
}
public void Update(GraphicsDevice graphics)
{
position += velocity;
if (position.X < 0 - texture.Width)
isVisible = false;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
}
I have genuinely tried many methods but it just doesn't seem to work.
Everything i've done so far gave me a "nullreferenceexception was unhandled" error.
I will take any criticism needed to improve.
Thank you for your help.
you need boundingBox property on your sprites
new Rectangle((int)Position.X,(int)Position.Y,texture.Width, texture.Height);
then to check collision
if (Sprite1.BoundingBox.Intersects(Sprite2.BoundingBox))
but make sure that you load your texture before any function that uses texture. i guess your error happened on update function where you try to get width of texture that is not loaded.

Having trouble with Sprite look at mouse in XNA for game

I understand that this question has been answered before and I've done my research trust me.
I'll say this now, this is a project for school but what I want to do this for my own learning considering that I will be going in to game programmer.
This might get messy but ill do my best
so for this its started as a basic shoot em up, we have a
game.cs- contains all the textures vectors what not, and the
entity.cs- has already begun spritebatch for player to call a player.draw (spritebatch) in
game.cs
player.cs- contains the shooting of the bullet and the position
bullet.cs
enemy.cs
So my problem is that I have the code for updating the sprite to look at the mouse then I would use
player.Draw(
playerTexture,
position,
null,
Color.White,
rotation,
spriteOrigin,
1.0f,SpriteEffects.None,0f);
In game.cs draw function, but when I do this I get another sprite (same sprite as my player sprite) that does look at my mouse but I want my other one to look at mouse
But my proff. Wrote the code so that there is an already begun spritebatch in entity.cs
public CEntity(CGame myGame, Texture2D myTexture)
{
game = myGame;
texture = myTexture;
}
/// <summary>
/// Draws the player.
/// </summary>
/// <param name="begunSpriteBatch">Give this function a already begun SpriteBatch.</param>
public void Draw(SpriteBatch begunSpriteBatch)
{
begunSpriteBatch.Draw(texture, position, Color.White);
}
So in game.cs draw function player.draw is called to draw the player, what can I do to get that look at mouse effect for that sprite?
public CPlayer(CGame game, Texture2D playerTexture)
: base(game, playerTexture)
{
texture = playerTexture;
brotation = rotation;
position.X = 400f;
position.Y = 400f;
}
And also player is inherited from entity.
Code for updating the mouse as requested
IsMouseVisible = true;
MouseState mouse = Mouse.GetState();
distance.X = mouse.X - position.X;
distance.Y = mouse.Y - position.Y;
//Math.Atan2((double)mouseState.Y - position.Y, (double)mouseState.X - position.X); was using this //before found a different way
rotation = (float)Math.Atan2(distance.Y, distance.X);
spriteRectangle = new Rectangle((int)position.X, (int)position.Y,//rotation stuff
playerTexture.Width, playerTexture.Height);
spriteOrigin = new Vector2(spriteRectangle.Width / 2, spriteRectangle.Height / 2);

Categories

Resources