Diagonal movement is faster than horizontal or vertical, 2D top down, left click to move
so pretty much what the title says, it has been answered before but since I use the mouse to move the recommentations dont work on my script
void FixedUpdate ()
{
GetComponent<Rigidbody2D> ().velocity = velocity;
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = +1;
if (Input.GetKey (KeyCode.Mouse0))
{
GetComponent<Rigidbody2D> ().freezeRotation = false;
velocity = (Camera.main.ScreenToWorldPoint(mousePosition) - gameObject.transform.position) * Time.deltaTime * 100f;
if (velocity.x >= MaxSpeed.x)
{
velocity.x = MaxSpeed.x;
}
if (-velocity.x >= MaxSpeed.x)
{
velocity.x = -MaxSpeed.x;
}
if (velocity.y >= MaxSpeed.y)
{
velocity.y = MaxSpeed.y;
}
if (-velocity.y >= MaxSpeed.y)
{
velocity.y = -MaxSpeed.y;
}
}
else
{
GetComponent<Rigidbody2D> ().freezeRotation = true;
velocity.x = 0f;
velocity.y = 0f;
}
}
Answer by Thajocoth · Jun 30, 2016 at 09:02 PM
The problem is that you're using separate max speeds for X & Y, which gives you a max speed box instead of a max speed circle. You need an absolute max speed.
const float maxSpeed = 10f;
float pythagoras = ((velocity.x * velocity.x) + (velocity.y * velocity.y));
if (pythagoras > (maxSpeed * maxSpeed))
{
float magnitude = sqrt(pythagoras);
float multiplier = maxSpeed / magnitude;
velocity.x *= multiplier;
velocity.y *= multiplier;
}
thanks a lot, this worked great, I never imagined I needed to use the pythagora's theory
I'm glad it helped!
Yeah, all the old math formulas come up now and then. For cartesian coordinates, Pythagoras comes up a lot, because the hypotenuse of the right triangle created by those cartesian coordinates is often useful. That's how you convert (x,y) to distance or (vx, vy) to speed.
Good luck with your game!
Thank you for this. I'm learning to code in lockdown. And I just realized a lot of math lessons at school can be very useful.