xirang/Assets/scripts/playercontroller.cs

64 lines
1.9 KiB
C#
Raw Normal View History

2024-11-26 22:01:14 +08:00
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;
2024-11-27 00:06:25 +08:00
public float rotationSpeed = 5f;
2024-11-26 22:01:14 +08:00
// Start is called before the first frame update
void Start()
{
2024-11-27 00:06:25 +08:00
playerController = GetComponent<CharacterController>();
2024-11-26 22:01:14 +08:00
}
// Update is called once per frame
void Update()
{
2024-11-27 00:06:25 +08:00
// <20><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>
x = Input.GetAxis("Horizontal");
y = Input.GetAxis("Vertical");
// <20><><EFBFBD><EFBFBD><EFBFBD>ƶ<EFBFBD><C6B6><EFBFBD><EFBFBD><EFBFBD>
2024-11-26 22:01:14 +08:00
moveDirection = new Vector3(x, 0, y);
moveDirection = transform.TransformDirection(moveDirection);
2024-11-27 00:06:25 +08:00
// <20><>ס<EFBFBD><D7A1>shift<66><74><EFBFBD><EFBFBD>
2024-11-26 22:01:14 +08:00
if (Input.GetKeyDown(KeyCode.LeftShift))
{
MaxSpeed *= 2;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
MaxSpeed /= 2;
}
moveDirection *= MaxSpeed;
2024-11-27 00:06:25 +08:00
// <20><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>λ<EFBFBD>ò<EFBFBD><C3B2><EFBFBD><EFBFBD>߼<EFBFBD><DFBC><EFBFBD>
2024-11-26 22:01:14 +08:00
Vector3 mouseScreenPosition = Input.mousePosition;
Ray ray = Camera.main.ScreenPointToRay(mouseScreenPosition);
RaycastHit hit;
2024-11-27 00:06:25 +08:00
2024-11-26 22:01:14 +08:00
if (Physics.Raycast(ray, out hit))
{
2024-11-27 00:06:25 +08:00
// <20><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>λ<EFBFBD>ã<EFBFBD><C3A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ŀ<EFBFBD><EFBFBD><EAB7BD>
Vector3 mouseWorldPosition = new Vector3(hit.point.x, transform.position.y, hit.point.z);
2024-11-26 22:01:14 +08:00
Vector3 direction = mouseWorldPosition - transform.position;
2024-11-27 00:06:25 +08:00
direction.y = 0;
// ʹ<><CAB9>Quaternion.Slerp<72><70><EFBFBD><EFBFBD>ƽ<EFBFBD><C6BD><EFBFBD><EFBFBD>ת
Quaternion targetRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
2024-11-26 22:01:14 +08:00
}
2024-11-27 00:06:25 +08:00
// <20>ƶ<EFBFBD><C6B6><EFBFBD><EFBFBD><EFBFBD>
2024-11-26 22:01:14 +08:00
playerController.Move(moveDirection * Time.deltaTime);
}
}