如何向操纵杆旋转GameObject

时间:2018-07-07 07:29:14

标签: c# unity3d joystick

因此,我正在创建一个自上而下的射击游戏,并试图使玩家面对操纵杆的方向。这是我当前的代码:

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")));
    }
}

出于某种原因,当我这样做时,它只是朝操纵杆的方向旋转得如此缓慢(似乎是每帧1度)。

1 个答案:

答案 0 :(得分:0)

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

接受eulerAngles和eulerAngles应该以度表示。您的参数不是度而是坐标。

您应该使用

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

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

您可以使用

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

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

获得所需的目标旋转