Hi. I wanted to make so my player can move up-down/left-right normally, but make so it always faces the mouse.
Currently, with the following code, it ‘kinda’ works. The player does face the mouse, but the movement is changed to that when I (for example) press the W key, instead of going up, it goes in the direction of the mouse. If I press S, instead of going down, it goes away from the mouse. Hope it makes sense.
private void PlayerMovement()
{
if (transform.position.x > -8 && transform.position.x < 8)
{
float horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * Time.deltaTime * horizontalInput * _speed);
}
else
{
if (transform.position.x > 8)
{
transform.Translate(Vector3.right * Time.deltaTime * (-0.1f) * _speed);
}
else if (transform.position.x < -8)
{
transform.Translate(Vector3.right * Time.deltaTime * 0.1f * _speed);
}
}
if (transform.position.y > -4 && transform.position.y < 4)
{
float verticallInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.up * Time.deltaTime * verticallInput * _speed);
}
else
{
if (transform.position.y > 4)
{
transform.Translate(Vector3.up * Time.deltaTime * (-0.1f) * _speed);
}
else if (transform.position.y < -4)
{
transform.Translate(Vector3.up * Time.deltaTime * 0.1f * _speed);
}
}
}
private void faceMouse()
{
Vector3 mousePos =
Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}