So yesterday i started to mess around a bit in unity3d and made a movement script for the player.
What i am trying to do is to make the character move in the same speed forward as diagonal forward and backwards as diagonal backwards. It works good on the right diagonal forward and backwards. The variable of the forward speed and backwardspeed gets “smaller” (9 down to 6 forward and 5 down to 2 backwards) when “d” is pressed and i have made the same thing for the “a” tangent but it dosent work. Heres the script!
I know it has some unessesary parts =D
.forward, .left , and .right are always going to unit vectors. So if you get a forward movement and a left movement we can just add the vectors together. However, that new vector that moves up diagonal will be bigger > 1 since we added to unit vectors to get it. That is why diagonal speed can be faster than left/up speed. Unity has a good way to handle this.
Vector3.Normalilze. Here’s an easy way to get those vectors added up (I also took out a lot of useless lines you had where you were multiplying things by 0 (that is effectively not doing the thing at all).
using UnityEngine;
public class MovementTest : MonoBehaviour
{
public float forwardSpeed = 10f;
public float backwardSpeed = 5f;
public float sidewaySpeed = 3f;
void Update()
{
Vector3 movementVector = Vector3.Zero; // variable to hold our total movment
float speed = forwardSpeed; // assume we are going forward and just change it if we detect back
//Forward
if (Input.GetKey("w"))
movementVector += Vector3.forward;
//Backwards
if (Input.GetKey("s"))
{
movementVector += Vector3.back; // If they push w and s at the same time they will just go back;
speed = backwardSpeed;
}
if (Input.GetKey("a"))
movementVector += Vector3.left;
//right
if (Input.GetKey("d"))
movementVector += movementVector.right;
// make it so forward is the same speed as forward+left
movementVector.Normalize();
transform.Translate(movementVector * speed * Time.deltaTime);
}
}
yes. Vector3.right is just a shortcut for new Vector3(1,0,0); Same for the others Vector3.forward is (0,0,1)
moveVector starts out at (0,0,0) and i’m just adding those other vectors to it, to get the final resultant vector. So if you press w and d together it will add (1,0,0) + (0,0,1) to get (1,0,1)