在Update()函数中加入以下代码来实现player触碰地面后改变地面颜色为红色的功能:

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        collision.gameObject.GetComponent<Renderer>().material.color = Color.red;
    }
}

完整的代码如下:

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;

    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)
        {
            _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<Renderer>().material.color = Color.red;
        }
    }
}
``
在该段代码中加入player触碰地面就改变player所处位置地面为红色功能:using System;using SystemCollections;using SystemCollectionsGeneric;using UnityEngine;public class PlayerScript MonoBehaviour public Transform follower; p

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

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