I am new to Unity and wanted to create a simple acceleration-based movement system that mimics an ice skater’s movement on an ice rink where the player uses keyboard input to change the direction of their movement and accelerate. But for some reason, this code doesn’t work even though the idea was very basic.
using System;
using UnityEngine;
public class Movement : MonoBehaviour
{
private float _mouseSensitivity = 3f;
private float velocity = 0;
private double vangle = 0; //velocity vector angle
private float fangle = 0; //angle player is facing
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
Vector2 Avector(float angle) { //generate a vector2 with magnitude 1 pointing in the angle direction
float rad = (float)Math.PI/180;
Vector2 v = new Vector2((float)Math.Sin(angle*rad),(float)Math.Cos(angle*rad));
return v;
}
// Update is called once per frame
void Update()
{
float rad = (float)Math.PI/180;
float timeDelta = Time.deltaTime;
//decceleration by 1/sec
if (velocity < timeDelta) {
velocity = 0;
} else {
velocity -= timeDelta;
}
float z = 0;
float x = 0;
//keyboard input
if (Input.GetKey(KeyCode.W)) z += 1f;
if (Input.GetKey(KeyCode.S)) z -= 1f;
if (Input.GetKey(KeyCode.D)) x += 1f;
if (Input.GetKey(KeyCode.A)) x -= 1f;
Vector2 v = new Vector2(velocity*(float)Math.Sin(vangle*rad),velocity*(float)Math.Cos(vangle*rad));
Vector2 v1 = 4*z*Avector(fangle);//accelerate by 4/s^2
Vector2 v0 = 4*x*Avector(fangle+90);
v+=(v1+v0)*timeDelta;//update velocity vector
velocity = v.magnitude;
vangle = Math.Atan2(v.y,v.x)*180/Math.PI;
if (velocity > 8) { //cap velocity at 8
float scale = 8f/velocity;
v.x*=scale;
v.y*=scale;
velocity = 8f;
}
Vector3 move = new Vector3(v.x, 0, v.y);
transform.position+=move*timeDelta; //move player
float mouseX = Input.GetAxis("Mouse X") * _mouseSensitivity;
fangle += mouseX;
transform.localEulerAngles+=new Vector3(0,mouseX,0);
}
}
The problem arises when I try to move, it seems that the velocity vector isn’t updating as it should and the direction associated with each key does not align with the local coordinate axis. This might be a consequence of the main problem, but the directional change of the velocity vector also isn’t smooth, the change in direction only happens once the velocity nears 0. I don’t know if this is a problem on my part or just a bug in the way movement works in unity.
The vangle
and fangle
are both relative to the forward direction (Y axis), so when calculating the angle with atan, the parameters should be swapped:
Math.Atan2(v.x,v.y)