【问题标题】:how to rotate GameObject towards joystick如何将游戏对象向操纵杆旋转
【发布时间】:2018-07-07 07:29:13
【问题描述】:

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

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 度)。

【问题讨论】:

    标签: c# unity3d joystick


    【解决方案1】:

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

    获得所需的目标旋转

    【讨论】:

    • 您的var rotation 在这种情况下的作用是什么
    • @DaanKoning 我编辑了答案-var rotation 现在是Quaternion targetRotation,可以用作Quaternion.RotateTowards 中的第二个参数
    • 我假设我只需要用我想去的 Vector3 替换 target.position? (Vector3(transform.position.x + Input.GetAxis("rightStickHorizontal"), transform.position.y, transform.position.z + Input.GetAxis("rightStickVertical"))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多