我正在Unity上制作自上而下的游戏,所以我将x和z轴用作平面。我将角色旋转x 90,y 0,z 0,以使其在平面上平整。我一点击播放,角色就会垂直旋转?!我认为这与我的脚本面对鼠标位置有关。
它应该是什么样子:
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9xclZOYS5wbmcifQ==” alt =“在此处输入图像描述”>
当我点击播放时:
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9UVXZ1RS5wbmcifQ==” alt =“在此处输入图像描述”>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public static float moveSpeed = 10f;
private Rigidbody rb;
private Vector3 moveInput;
private Vector3 moveVelocity;
// Update is called once per frame
void Start()
{
rb = GetComponent<Rigidbody>();
mainCamera = FindObjectOfType<Camera>();
}
void Update()
{
// Setting up movement along x and z axis. (Top Down Shooter)
moveInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
moveVelocity = moveInput * moveSpeed;
//Make character look at mouse.
var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
}
void FixedUpdate()
{
// Allows character to move.
rb.velocity = moveVelocity;
}
}
这可能对您有帮助。将此代码插入播放器,然后跟随鼠标旋转。
Vector3 mouse = Input.mousePosition;
Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(new Vector3(
mouse.x,
mouse.y,
player.transform.position.y));
Vector3 forward = mouseWorld - player.transform.position;
player.transform.rotation = Quaternion.LookRotation(forward, Vector3.up);