改正改代码:using System;using SystemCollections;using SystemCollectionsGeneric;using UnityEngine;public class PlayerScript MonoBehaviour public Transform follower; private Rigidbody _playerRigidbody
using System; using UnityEngine;
public class PlayerScript : MonoBehaviour { public Transform follower; private Rigidbody _playerRigidbody; private Vector3 _controlToGoForward = new Vector3(0, 0, 10); private Vector3 _controlToGoLeft = new Vector3(-10, 0, 0); private Vector3 _controlToGoRight = new Vector3(10, 0, 0); private Vector3 _controlToJump = new Vector3(0, 5, 0); private Vector3 _controlToGoBack = new Vector3(0, 0, -10); private bool _isKeySpaceTyped;
public GameObject detectionArea; // 检测区域物体
private bool _isGrounded; // 是否接触地面
private Material _originalMaterial; // 原始材质
public Material redMaterial; // 红色材质
void Start()
{
_playerRigidbody = GetComponent<Rigidbody>();
detectionArea = GameObject.FindGameObjectWithTag("player"); // 根据标签查找检测区域物体
_originalMaterial = detectionArea.GetComponent<MeshRenderer>().material;
}
void Update()
{
bool isKeyRTyped = Input.GetKey(KeyCode.R);
bool isKeyTTyped = Input.GetKey(KeyCode.T);
bool isKeyWTyped = Input.GetKey(KeyCode.W);
bool isKeyATyped = Input.GetKey(KeyCode.A);
bool isKeySTyped = Input.GetKey(KeyCode.S);
bool isKeyDTyped = Input.GetKey(KeyCode.D);
bool isKeyShiftTyped = Input.GetKey(KeyCode.LeftShift);
float mouseMoveX = Input.GetAxis("Mouse X");
float mouseMoveY = Input.GetAxis("Mouse Y");
float mouseCausedMovedPara = 5;
_isKeySpaceTyped = Input.GetKey(KeyCode.Space);
if (isKeyWTyped)
{
_playerRigidbody.AddForce(_controlToGoForward * Time.deltaTime);
}
if (isKeyATyped)
{
_playerRigidbody.AddForce(_controlToGoLeft * Time.deltaTime);
}
if (isKeySTyped)
{
_playerRigidbody.AddForce(_controlToGoBack * Time.deltaTime);
}
if (isKeyDTyped)
{
_playerRigidbody.AddForce(_controlToGoRight * Time.deltaTime);
}
if (_isKeySpaceTyped && _isGrounded)
{
_playerRigidbody.AddForce(_controlToJump * Time.deltaTime, ForceMode.Impulse);
}
if (isKeyRTyped)
{
transform.position = new Vector3(-20, 68, -30);
}
follower.Rotate(-mouseMoveY * mouseCausedMovedPara, mouseMoveX * mouseCausedMovedPara, 0);
if (isKeyTTyped)
{
follower.Rotate(-follower.rotation.x, -follower.rotation.y + 1, -follower.rotation.z);
}
}
void OnCollisionEnter(Collision collision)
{
// 如果检测到碰撞对象是地面
if (collision.gameObject.CompareTag("dirt"))
{
_isGrounded = true; // 玩家接触地面
detectionArea.GetComponent<MeshRenderer>().material = redMaterial; // 将接触面材质设置为红色
}
}
void OnCollisionExit(Collision collision)
{
// 如果检测到离开碰撞对象是地面
if (collision.gameObject.CompareTag("dirt"))
{
_isGrounded = false; // 玩家离开地面
detectionArea.GetComponent<MeshRenderer>().material = _originalMaterial; // 将接触面材质恢复为原始材质
}
}
原文地址: https://www.cveoy.top/t/topic/hPjq 著作权归作者所有。请勿转载和采集!