- Home /
Problems with diagonal movement.
Hey, i know this is a common question, but the answers i have found, can't be aplied to my problem because of an anoying extra layer.
So the problem in question is that my player moves faster while moving diagonally, due to the velocity vector getting doubled.
The usual fix for this would be to either multiply it by .7 when moving diagonally, or normalize the value. But this isn't enough for my problem, because i have smoothed out my movement with an acceleration and decceleration. If i normalize the value, it will only work when at full speed, and changing speeds will not make it accelerate / deccelerate to the new speed. I can't seem to find a way to do this, here is the code i have been using so far:
Vector3 targetDirection = Vector3.zero;
targetDirection.x = Input.GetAxisRaw("Horizontal");
targetDirection.z = Input.GetAxisRaw("Vertical");
if (targetDirection.x != 0f)
{
velocity.x = Mathf.MoveTowards(velocity.x, speedCap * targetDirection.x, accel * Time.deltaTime);
}
else
{
velocity.x = Mathf.MoveTowards(velocity.x, 0f, deccel * Time.deltaTime);
}
if (targetDirection.z != 0f)
{
velocity.z = Mathf.MoveTowards(velocity.z, speedCap * targetDirection.z, accel * Time.deltaTime);
}
else
{
velocity.z = Mathf.MoveTowards(velocity.z, 0f, deccel * Time.deltaTime);
}
transform.position += velocity * 25 * Time.deltaTime;
So, i think i need to somehow clamp my velocity, to a magnitude, that is it's current velocity? It's pretty hard for me to understand it so if someone could help out it would be awesome.
Answer by $$anonymous$$ · Jul 29, 2019 at 03:31 PM
Damn i feel so stupid, i just fixed it myself and the solution was litteraly on my nose.
If anyones facing the same problem, then first of all, i pity you for being as dumb as me sorry. Here it is:
Instead of normalizing the velocity, normalize the damn input :/
Heres the working code
Vector3 targetDirection = Vector3.zero;
targetDirection.x = Input.GetAxisRaw("Horizontal");
targetDirection.z = Input.GetAxisRaw("Vertical");
targetDirection.Normalize(); //This is the line.
if (targetDirection.x != 0f)
{
velocity.x = Mathf.MoveTowards(velocity.x, speedCap * targetDirection.x, accel * Time.deltaTime);
}
else
{
velocity.x = Mathf.MoveTowards(velocity.x, 0f, deccel * Time.deltaTime);
}
if (targetDirection.z != 0f)
{
velocity.z = Mathf.MoveTowards(velocity.z, speedCap * targetDirection.z, accel * Time.deltaTime);
}
else
{
velocity.z = Mathf.MoveTowards(velocity.z, 0f, deccel * Time.deltaTime);
}
transform.position += velocity * 25 * Time.deltaTime;
One line that's all.
Your answer
Follow this Question
Related Questions
Does anyone know what i am doing wrong? 0 Answers
Moving tram along rail. 0 Answers
Velocity is not matching the Vector3 it is assigned 1 Answer
I have a movement script, but how can i make it so i can move half the speed while in the air. 0 Answers
Character Transform shifting after colliding with objects 0 Answers