Hello. I’m trying to make my game controllable with an analog stick, but the player doesn’t seem to move quite right. Here’s what I have for my player’s script:
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour {
public Camera camera;
public float currentAngle = 0;
public float previousAngle = 0;
public float speed = 0;
public float walkingSpeed = 1;
public Vector3 analogDirection;
public Vector3 velocity;
// Use this for initialization
void Start () {
velocity = new Vector3(0,0,0);
analogDirection = new Vector3(0,0,0);
}
// Update is called once per frame
void Update () {
GetAngle();
GetVelocity();
MovePlayer();
}
private void GetAngle(){
//PlayerCamera cameraScript = camera.GetComponent<PlayerCamera>;
float inputAngle = (Mathf.Rad2Deg * Mathf.Atan2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")));
analogDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
previousAngle = currentAngle;
//TODO: Rotate the current angle proportionally with the camera angle
currentAngle = inputAngle;
}
private void GetVelocity(){
speed = walkingSpeed * analogDirection.magnitude;
velocity.x = Mathf.Rad2Deg * Mathf.Cos(currentAngle) * speed;
velocity.z = Mathf.Rad2Deg * Mathf.Sin(currentAngle) * speed;
}
private void MovePlayer(){
Vector3 myPos = transform.position;
myPos += velocity * Time.deltaTime;
transform.position = myPos;
}
}
The issue I have here is that when I push the analog stick forward, my player goes diagonal. According to the inspector, when currentAngle = 90, then velocity.x =~ -25, and velocity.z =~ 51.2. This doesn’t make sense, though. Shouldn’t it be that velocity.x = 0 and velocity.z =~ 58? The inspector is correctly reporting that analogDirection.z is 1, so there should be no reason why I’m getting this reslut.
Anyone have any explanation as to why this is? How can I fix it?