64 lines
1.9 KiB
C#
64 lines
1.9 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
|
|
public class playercontroller : MonoBehaviour
|
|
{
|
|
CharacterController playerController;
|
|
public Vector3 moveDirection = Vector3.zero;
|
|
public float MaxSpeed = 10;
|
|
public float x;
|
|
public float y;
|
|
public float rotationSpeed = 5f;
|
|
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
playerController = GetComponent<CharacterController>();
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
// 获取输入
|
|
x = Input.GetAxis("Horizontal");
|
|
y = Input.GetAxis("Vertical");
|
|
|
|
// 计算移动方向
|
|
moveDirection = new Vector3(x, 0, y);
|
|
moveDirection = transform.TransformDirection(moveDirection);
|
|
|
|
// 按住左shift加速
|
|
if (Input.GetKeyDown(KeyCode.LeftShift))
|
|
{
|
|
MaxSpeed *= 2;
|
|
}
|
|
if (Input.GetKeyUp(KeyCode.LeftShift))
|
|
{
|
|
MaxSpeed /= 2;
|
|
}
|
|
moveDirection *= MaxSpeed;
|
|
|
|
// 获取鼠标位置并射线检测
|
|
Vector3 mouseScreenPosition = Input.mousePosition;
|
|
Ray ray = Camera.main.ScreenPointToRay(mouseScreenPosition);
|
|
RaycastHit hit;
|
|
|
|
if (Physics.Raycast(ray, out hit))
|
|
{
|
|
// 获取鼠标点击的世界位置,并计算目标方向
|
|
Vector3 mouseWorldPosition = new Vector3(hit.point.x, transform.position.y, hit.point.z);
|
|
Vector3 direction = mouseWorldPosition - transform.position;
|
|
direction.y = 0;
|
|
|
|
// 使用Quaternion.Slerp进行平滑旋转
|
|
Quaternion targetRotation = Quaternion.LookRotation(direction);
|
|
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
|
|
}
|
|
|
|
// 移动玩家
|
|
playerController.Move(moveDirection * Time.deltaTime);
|
|
}
|
|
}
|