原输入系统:
Input.mousePosition
InputSystem下:
using UnityEngine.InputSystem;
Mouse.current.position.ReadValue()
对象跟随鼠标旋转:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class GunFollowMouse : MonoBehaviour
{
[SerializeField] float rotationSpeed = 6f;
float angle;
Vector2 direction;
Quaternion rotation;
Vector3 mouseposition;
private void OnEnable()
{
StartCoroutine(nameof(GunRotation));
}
private void OnDisable()
{
StopCoroutine(nameof(GunRotation));
}
IEnumerator GunRotation()
{
while (true)
{
mouseposition = Input.mousePosition;
mouseposition.z = 6f; //在坐标转换时,z轴坐标必须不为0,否则只会转换一次,表现上就是转卡住了
direction = Camera.main.ScreenToWorldPoint(mouseposition) - transform.position;
angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
yield return null;
}
}
}