如何将游戏对象旋转到操纵杆
how to rotate GameObject towards 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 度)。
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);
获得所需的目标旋转
所以我正在创建一个自上而下的射击游戏,并试图让玩家面对操纵杆的方向。这是我当前的代码:
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 度)。
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);
获得所需的目标旋转