- Home /
Question by
ownedbycow_unity · Sep 20, 2021 at 10:26 PM ·
rotationunity 2dcharacter movement
Cannot get my character to rotate on Z axis. --Top Down Character View
I was following a tutorial to try to make my movement and rotation code a bit easier to read and not redundant. I got to this part of the coding and realized that it would not work as I needed it to. In this script it has the character moving on the X and Z axis while rotating on the Y. I want to have my character move on the X and Y axis while rotation is on Z. I have two scripts that I have attached. There is a comment separating the two.
I've tried converting lines into Vector3 from quaternion, but that just causes the rotation to not work at all. If I switch up the Y and Z on the one line below, it causes rotation to happen on both X and Y and its completely broken.
public class playerMoveAttack : MonoBehaviour
{
private InputHandler playerInput;
[SerializeField] private float moveSpeed;
[SerializeField] private float rotateSpeed;
private void Awake()
{
playerInput = GetComponent<InputHandler>();
}
void Update()
{
//Rotation works right this way but I need movement on X and Y. This rotates correctly on Y
var targetVector = new Vector3(playerInput.InputVector.x, 0, playerInput.InputVector.y);
//Movement is now on X and Y with this line but rotations do not work at all now.
// var targetVector = new Vector3(playerInput.InputVector.x, playerInput.InputVector.y, 0);
//move in dir of aim
var movementVector = MoveTowardTarget(targetVector);
//rotate to dir of aim
RotateTowardMovementVector(movementVector);
}
private void RotateTowardMovementVector(Vector3 movementVector)
{
if (movementVector.magnitude == 0) {return; }
var rotation = Quaternion.LookRotation(movementVector);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, rotateSpeed);
}
private Vector3 MoveTowardTarget(Vector3 targetVector)
{
var speed = moveSpeed * Time.deltaTime;
transform.Translate(targetVector * speed);
return targetVector;
}
}
//Script 2 starts here
public class InputHandler : MonoBehaviour
{
public Vector2 InputVector { get; private set; }
void Update()
{
var h = Input.GetAxis("Horizontal");
var v = Input.GetAxis("Vertical");
InputVector = new Vector2(h, v);
}
}
Comment