1

So I'm creating a top-down shooter and trying to make the player face the direction of the joystick. this is my current code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour {

    Camera cam;
    PlayerMotor motor;

    void Start () {
        cam = Camera.main;
        motor = GetComponent<PlayerMotor>();
    }

    void Update () {
        //movement
        motor.MoveToPoint(new Vector3(transform.position.x + Input.GetAxis("Horizontal"), transform.position.y, transform.position.z + Input.GetAxis("Vertical")));

        //cam control
        cam.transform.position = new Vector3(transform.position.x,
        transform.position.y + 9.0f,
        transform.position.z);

        //this is the problem
        transform.Rotate(new Vector3(transform.position.x + Input.GetAxis("rightStickHorizontal"), transform.position.y, transform.position.z + Input.GetAxis("rightStickVertical")));
    }
}

for some reason when I do this it just turns ever so slowly in the direction of the joystick (appears to be 1 degree per frame).

Daan Koning
  • 155
  • 2
  • 15

1 Answers1

0

transform.Rotate https://docs.unity3d.com/ScriptReference/Transform.Rotate.html

accepts eulerAngles and eulerAngles should be expressed in degrees. your parameters are not degrees but coordinates.

instead you should use

https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html

transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime);

you can use

https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html

Vector3 relativePos = target.position - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(relativePos);

to get the desired target rotation

Jinjinov
  • 2,554
  • 4
  • 26
  • 45
  • what purpose does your `var rotation` serve in this context – Daan Koning Jul 09 '18 at 19:06
  • @DaanKoning i edited the answer - `var rotation` is now `Quaternion targetRotation` that can be used as the second parameter in `Quaternion.RotateTowards` – Jinjinov Jul 09 '18 at 21:35
  • and I assume that I'd just have to replace `target.position` with a Vector3 of where I want to go? (`Vector3(transform.position.x + Input.GetAxis("rightStickHorizontal"), transform.position.y, transform.position.z + Input.GetAxis("rightStickVertical")`) – Daan Koning Jul 10 '18 at 08:37