我最近开始学习如何编码,我真的很喜欢它,我有点卡住了,我想得到你的帮助。我已经添加:
- 一架飞机
- 角色 Controller (在层次结构中名为“Matt”)
- 一个立方体(它应该在按键时将颜色更改为红色,如果 角色 Controller 与立方体上的对撞机发生碰撞)+脚本 附在立方体上
如果按下 R 键(有效)或者玩家 Controller 与立方体的碰撞器发生碰撞,我希望立方体改变它的颜色。
Screenshot of my scene below
using UnityEngine;
using System.Collections;
public class colorChange : MonoBehaviour
{
public GameObject cube;
private Renderer rend;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
// This will get the OBJECT to CHANGE COLOR on KEY PRESS
if (Input.GetKeyDown (KeyCode.R))
GetComponent<Renderer> ().material.color = Color.red;
print ("A Key Pressed For Red Color");
}
void OnCollisionEnter (Collision col)
{
if (col.collider.name == "Matt")
{
rend.material.color = Color.yellow;
}
}
}
这是两个对象的属性截图:
最佳答案
碰撞检测的复杂之处在于您使用的是角色 Controller ,它在 Unity 的物理模拟中并不完全有效。因此 OnCollisionEnter()
永远不会在角色 Controller 和普通碰撞器之间的碰撞期间被调用。
听起来您需要的是 OnControllerColliderHit()
方法。根据文档:
OnControllerColliderHit is called when the controller hits a collider while performing a Move.
但是,请注意接收事件的是角色 Controller ,而不是它撞到的对象。因此,如果您确实修改代码以使用它,则需要使用 Controller 将事件放在 GameObject 上,并从那里检测/更改立方体的渲染器颜色:
void OnControllerColliderHit(ControllerColliderHit col) {
if (col.collider.name == "cube")
{
col.gameObject.GetComponent<Renderer>().material.color = Color.yellow;
}
}
注意:由于与使用 Unity 的角色 Controller 相关的所有与物理相关的麻烦,您实际上可能想要使用刚体和胶囊碰撞器创建您自己的版本。这将需要更多的脚本编写,但 Unity 提供的解决方案确实不能很好地与引擎的其他部分配合使用。
希望对您有所帮助!如果您有任何问题,请告诉我。
关于c# - 在与角色 Controller /C# 发生碰撞时更改立方体的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41881380/