xirang/Assets/scripts/playercontroller.cs

48 lines
1.5 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;
// 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);
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, hit.point.y, hit.point.z);
Vector3 direction = mouseWorldPosition - transform.position;
Quaternion rotation = Quaternion.LookRotation(direction);
transform.rotation = rotation;
}
playerController.Move(moveDirection * Time.deltaTime);
}
}