I’m very new to Unity and C#, but not to programming. I have had experience with Gamemaker and 2d games, and found the best way to make player movement in those cases was with Vertical and Horizontal Speed variables (VSP and HSP). I tried this in unity using that idea with my limited knowledge of Unity to make the following. It works alright for the most part, but when I move vertically (along the z axis) it moves slightly left, and when I move horizontally, it moves slightly down. I could use some help either finding what is wrong with this, or developing another movement script altogether. Thanks!
using UnityEngine;
public class Player_Movement : MonoBehaviour
{
public Rigidbody Player;
private float up;
private float down;
private float right;
private float left;
public float Walkspeed;
private float VMove;
private float HMove;
private float VSP = 0;
private float HSP = 0;
public float MaxSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//getting key presses
if (Input.GetKey("w"))
{
up = 1;
}
else
{
up = 0;
}
if (Input.GetKey("s"))
{
down = 1;
}
else
{
down = 0;
}
if (Input.GetKey("a"))
{
left = 1;
}
else
{
left = 0;
}
if (Input.GetKey("d"))
{
right = 1;
}
else
{
right = 0;
}
VMove = up - down;
HMove = right - left;
VSP = VSP + (VMove * Walkspeed);
HSP = HSP + (HMove * Walkspeed);
if (VMove == 0)
{
VSP = VSP - (Walkspeed * Mathf.Sign(VSP));
}
if (HMove == 0)
{
HSP = HSP - (Walkspeed * Mathf.Sign(HSP));
}
if (Mathf.Abs(VSP) >= MaxSpeed)
{
VSP = (Mathf.Sign(VSP) * Walkspeed);
}
if (Mathf.Abs(HSP) >= MaxSpeed)
{
HSP = (Mathf.Sign(HSP) * Walkspeed);
}
Player.AddForce(HSP * Time.deltaTime, 0, VSP * Time.deltaTime, ForceMode.VelocityChange);
}
}