- Home /
Diagonal Movement
Hello guys, I'm with one doubt, related to the diagonal movement, I've searched for questions like this, but the diagonal script movement is already made, so as a beginner I have a doubt about how can i do the diagonal movement, I'm using a script like this to make the movement of anything:
void Update() {
if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) {
transform.Translate(Vector3.forward*SpeedZ);
}
else if(Input.GetKey(KeyCode.S)||Input.GetKey(KeyCode.DownArrow)) {
transform.Translate(Vector3.back*SpeedZ);
}
else if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) {
transform.Translate(Vector3.left*SpeedX);
}
else if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) {
transform.Translate(Vector3.right*SpeedX);
}
}
So the diagonal movement is described by the drawing that I've made
The Cartesian plane that I've made, representing the vectors of the movement, and the vectors of the diagonal movement, so my question is, how can I do it? I've thought in divide by e.g the vectors W by D to achieve the diagonal movement forward right, something like that:
Vector2 diagonal = W_Movement/D_Movement;
The W_Movement is a Vector, so I don't know if this is right, I want to understand how it works in the Cartesian plane, and if my propose it's right!
Answer by robertbu · Oct 30, 2013 at 06:49 AM
The way to get a diagonal is to add the two vectors together. You will want to normalize the result. If you give up on independent speed for x and z, you can rework you code as follows:
var speed = 2.0;
function Update() {
var v3 : Vector3;
if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) {
v3 += Vector3.forward;
}
if(Input.GetKey(KeyCode.S)||Input.GetKey(KeyCode.DownArrow)) {
v3 += Vector3.back;
}
if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) {
v3 += Vector3.left;
}
else if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) {
v3 += Vector3.right;
}
transform.Translate(speed * v3.normalized * Time.deltaTime);
}
FYI: this code can be written much simpler with Input.GetAxis(). The 'Horizontal' and 'Vertical' axes are already setup and include the keys you are using. Example:
var speed = 2.0;
function Update() {
var v3 = Vector3(Input.GetAxisRaw("Horizontal"), 0.0, Input.GetAxisRaw("Vertical"));
transform.Translate(speed * v3.normalized * Time.deltaTime);
}
Note if you replace 'GetAxisRaw' with 'GetAxis' in the two places it is used, your object will have a bit of momentum carry through.
Thanks for the answer, really gives a great explain to me :D
For any beginners who are reading this in 2018
var v3 = new Vector3(Input.GetAxisRaw("Horizontal"), 0.0, Input.GetAxisRaw("Vertical"));
that might confuse some people so i thought i'd comment this