- Home /
How to make a character move both vertically and horizontally on a plane?
So basically my issue is the following - my character only moves in a horizontal line, how to make it possible for it to go both ways? Here's a snippet of that part, I am stuck on the vector and the designated position.
void FixedUpdate()
{
if (take_input)
{
float h = Input.GetAxis("Horizontal");
float push;
if (h > 0)
push = 1;
else if (h < 0)
push = -1;
else
push = 0;
leg_anim.SetFloat("speed", Mathf.Abs(push));
rb2d.position += my_speed * Vector2.right * push * Time.deltaTime;
if (h > 0 && !facingRight)
Flip();
else if (h < 0 && facingRight)
Flip();
Answer by JSierraAKAMC · Oct 25, 2017 at 10:23 PM
I'm not sure if this will work because I don't know if there's a gravitational force acting on the character or anything that is currently altering the vertical position, but you can use the current as a guide on how to do vertical movement. However, it appears that you are using a Rigidbody2D component "rb2d.position += ..." so the gravity modifier must be turned off if it isn't already, which may cause other issues.
Try this, and if it doesn't work, let me know and I'll do my best to help you further.
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical"); //Get vertical input
float hPush, vPush; //Horizontal and vertical push
if ( h > 0)
hPush = 1;
else if (h < 0)
hPush = -1;
else
hPush = 0;
//Do the same for vertical
if (v > 0)
vPush = 1;
else if (v < 0)
vPush = -1;
else
vPush = 0;
leg_anim.SetFloat("speed", Mathf.Abs(hPush)); //Will only be based on horizontal movement--I don't know your desired outcome
Vector2 addPosition = my_speed * (Vector2.right * hPush) + (Vector2.up * vPush) * Time.deltaTime; //Untested, but should work
rb2d.position += addPosition; //Separated for clarity
Your answer
