Files
3d-qiaozha/Assets/Scripts/WorkerMove1.cs
2026-03-10 10:07:11 +08:00

77 lines
2.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Cinemachine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorkerMove1 : MonoBehaviour
{
private CharacterController chara;
public float MoveSpeed = 4f;
public CinemachineFreeLook freeLook;
private float Gravity = -9.8f;
private float yVelocity = 0f;
public Transform Foot;
// Start is called before the first frame update
void Start()
{
chara = GetComponent<CharacterController>();
//Cursor.visible = false;
//Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
MoveSpeed = 8f;
}
else
{
MoveSpeed = 4f;
}
if (IsGround())
{
yVelocity = 0f;
}
else
{
yVelocity += Gravity * Time.deltaTime;
}
chara.Move(new Vector3(0f, yVelocity, 0f) * Time.deltaTime);
KeyControl();
}
private void KeyControl()
{
Vector3 cameraWorldPos = freeLook.transform.position;
// 2. 获取Look At目标的世界位置FreeLook的LookAt属性
Vector3 lookAtWorldPos = freeLook.LookAt.position;
// 3. 计算相机看向目标的世界方向(归一化,仅保留方向)
Vector3 lookAtWorldDir = (lookAtWorldPos - cameraWorldPos).normalized;
float x = lookAtWorldDir.x;
float z = lookAtWorldDir.z;
Vector3 xyz = new Vector3(x, 0, z).normalized;
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 forwardMove = xyz * vertical;
Vector3 rightMove = transform.right * horizontal;
Vector3 move = forwardMove + rightMove;
Vector3 realMove = move.normalized * MoveSpeed * Time.deltaTime;
chara.Move(realMove);
if (move.sqrMagnitude > 0f)
{
Quaternion targetRotation = Quaternion.LookRotation(xyz);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10f);
}
}
bool IsGround()
{
return Physics.CheckSphere(Foot.position, 0.01f);
}
}