- Home /
Why are my controls laggy
So I wrote a basic script that checks what button is being pressed and moves you in that direction but nothing seems to happen unless you hold the keys down. For example if I tap on the "a" key the player stands still, but if I hold the A key the player moves.
public class Player : MonoBehaviour
{
[SerializeField]
private float speed = 10;
private Vector2 direction = Vector2.zero;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
_Input();
Move(direction);
}
public void _Input()
{
direction = Vector2.zero;
if (Input.GetAxis("Horizontal") == 1)
{
direction += Vector2.right;
}
else if (Input.GetAxis("Horizontal") == -1)
{
direction += Vector2.left;
}
if (Input.GetAxis("Vertical") == 1)
{
direction += Vector2.up;
}
else if (Input.GetAxis("Vertical") == -1)
{
direction += Vector2.down;
}
}
public void Move(Vector2 _direction)
{
transform.Translate(_direction * speed * Time.deltaTime);
}
}
Answer by Vega4Life · Jul 31, 2019 at 04:59 PM
A couple of things to think about. First, you really only need to do this for your input:
Vector3 direction; // Change to Vector 3
public void _Input()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
}
public void Move(Vector2 _direction)
{
transform.Translate(_direction * speed * Time.deltaTime);
}
Next, GetAxis has smoothing. Meaning, it ramps from 0 to 1. Thus why you need to hold it to get up to max speed. If you don't want that to happen, you have two options: You can normalize the direction vector OR use GetAxisRaw (I tend to do this one).
direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
OR
direction = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
This makes it so the direction vector will either be 0 or 1... without any smoothing.
Hope this helps.
Your answer
Follow this Question
Related Questions
Why isn't my instance of an object moving? 1 Answer
2D Movement with axis? 1 Answer
AI Movement Direction 0 Answers
My Touch Movement Script is Not Working Correctly 1 Answer
Object some times goes off screen 0 Answers