- Home /
Why is going one direction faster
Okay so i have a simple basic code for moving ,]------------------
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Ballcontroller2 : MonoBehaviour {
public float movespeed;
private Rigidbody myrigidbody;
private Vector3 moveInput;
private Vector3 moveVelocity;
// Use this for initialization
void Start () {
myrigidbody = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
moveInput = new Vector3 (Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
moveVelocity = moveInput * movespeed;
}
void FixedUpdate () {
myrigidbody.velocity = moveVelocity;
}
}
but everytime i press up and left at the same time the speed is faster than if i press up by or left by itself
is there a way to fix that so that the speed is the same? picture below should help what im saying by up-left
Thanks in advance!
Answer by Leucaruth · Jun 13, 2017 at 04:20 PM
Hi.
Tthis is a common problem. It's related to the pythagorean theorem.
You must think with directions as if they were inside a circle, as you are doing right now it's as if they were inside a square. This means that when you push diagonally you are creating a vector which magnitude is 1.4142, and when you are pushing only one axis, horizontal or vertical, you are creating a vector which magnitude is only 1.
You can see how this works in this image:
To make your movement homogeneous, you need to "normalize" your vector, this is done automatically by unity if you write ".normalize" after your vector, so if you change your line of code:
moveVelocity = moveInput * movespeed;
with this one:
moveVelocity = moveInput.normalized * movespeed;
your problem will be solved.
If you are curious I recommend you to search more about vectors as you will need a good knowledge about them in Unity.
Thanks a lot! it worked just fine and i will take your advice and do more research on Vectors. Once again thank you for your help
:) byrd
You are welcome ^^. I'm glad if I was of some help.