using System; using System.Collections; using System.Collections.Generic; 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; private bool _isTouchingGround; // 新增变量,记录是否接触到地面

void Start()
{
    _playerRigidbody = GetComponent<Rigidbody>();
    
}


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);
    }
    
    if (isKeyATyped)
    {
        _playerRigidbody.AddForce(_controlToGoLeft);
    }
    
    if (isKeySTyped)
    {
        _playerRigidbody.AddForce(_controlToGoBack);
    }
    
    if (isKeyDTyped)
    {
        _playerRigidbody.AddForce(_controlToGoRight);
    }
    
    if (_isKeySpaceTyped && _isTouchingGround) // 需要同时按下空格键且处于地面上才能跳跃
    {
        _playerRigidbody.AddForce(_controlToJump);
    }
    
    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("Ground")) // 判断是否和地面碰撞
    {
        collision.gameObject.GetComponent<MeshRenderer>().material.color = Color.red; // 改变地面颜色为红色
        _isTouchingGround = true; // 标记玩家接触到地面
    }
}

void OnCollisionExit(Collision collision)
{
    if (collision.gameObject.CompareTag("Ground")) // 判断是否和地面离开碰撞
    {
        collision.gameObject.GetComponent<MeshRenderer>().material.color = Color.white; // 恢复地面原材质颜色
        _isTouchingGround = false; // 标记玩家离开地面
    }
}
在该段代码中加入player触碰地面就改变player所处位置地面为红色并在跳起后恢复原材质功能:using System;using SystemCollections;using SystemCollectionsGeneric;using UnityEngine;public class PlayerScript MonoBehaviour public Transform foll

原文地址: https://www.cveoy.top/t/topic/hPkZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录