- Home /
Moving my character horizontally and vertically at diffrent times
Im trying to make a movement code that when you move horizontally you can't go vertically with my vertically code and vice-versa. can someone help me please
Answer by Bluk · Aug 11, 2015 at 07:58 PM
Assuming your character has a rigidbody, you can do something like:
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
//We are not currently moving on the x axis
if (rb.velocity.x != 0) {
moveVertical = 0;
}
//We are not currently moving on the y axis
else if (rb.velocity.y != 0) {
moveHorizontal = 0;
}
Vector3 Movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce(Movement);
}
Or if you move in some other way just set movingX and movingY booleans so that only the part of code on the correct axis is executed
im not the best in unity but why do you have the ! between the x and the 0
it didn't work and I have a rigid body. can you check my script. it updated the api
using UnityEngine; using System.Collections;
public class PlayerControl : $$anonymous$$onoBehaviour {
public float speed;
private Rigidbody rb;
void Start () {
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 $$anonymous$$ovement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce($$anonymous$$ovement * speed);
if (GetComponent<Rigidbody>().velocity.x != 0) {
GetComponent<Rigidbody>().velocity.y = 0;
}
else if (GetComponent<Rigidbody>().velocity.y != 0) {
GetComponent<Rigidbody>().velocity.x = 0;
}
}
}
!= means "different from"
If you initialize rb to be GetComponent(); in start (a good thing) use it in Update() !
I edit my answer with the new version. It works for me.
you could use
if(Input.GetAxis("Horizontal") != 0)
{
//write Left Right Code
}
else if(Input.GetAxis("Vertical") != 0)
{
//write updown Code
}
this works because it will only run the first block to be true.
so the Vertical and Horizotnal will never work at the same time
Your answer
![](https://koobas.hobune.stream/wayback/20220611235421im_/https://answers.unity.com/themes/thub/images/avi.jpg)