unity3d如何进行碰撞检测

2025-10-29 17:36:41

1、新建一个文件夹,存放脚本

unity3d如何进行碰撞检测

2、新建一个平面,作为地面

unity3d如何进行碰撞检测

unity3d如何进行碰撞检测

3、添加平行光

unity3d如何进行碰撞检测

4、新建一个Cube,按“Ctrl + D”,可以复制Cube

unity3d如何进行碰撞检测

5、选中4个Cube,添加刚体

unity3d如何进行碰撞检测

6、把4个Cube分别命名为“c1、c2、c3、c4”

unity3d如何进行碰撞检测

7、新建一个C#脚本,命名为:Move

截图好像早了,具体请看文本的代码

“Move”脚本丢给摄像机

unity3d如何进行碰撞检测

8、编写代码:

using UnityEngine;

using System.Collections;

public class Move : MonoBehaviour {

GameObject go;//

// Use this for initialization

void Start () {

go = GameObject.Find("c4");

go.renderer.material.color = Color.red;

}

// Update is called once per frame

void Update () {

if(Input.GetKey(KeyCode.W))

{

go.transform.Translate(0,0,5*Time.deltaTime,Space.Self);

}

if(Input.GetKey(KeyCode.S))

{

go.transform.Translate(0,0,-5*Time.deltaTime,Space.Self);

}

if(Input.GetKey(KeyCode.A))

{

go.transform.Translate(-5*Time.deltaTime,0,0,Space.Self);

}

if(Input.GetKey(KeyCode.D))

{

go.transform.Translate(5*Time.deltaTime,0,0,Space.Self);

}

}

}

unity3d如何进行碰撞检测

unity3d如何进行碰撞检测

unity3d如何进行碰撞检测

unity3d如何进行碰撞检测

9、新建一个C#脚本,命名为:pzjc

“pzjc”脚本丢给"c4"

代码如下:

using UnityEngine;

using System.Collections;

public class pzjc : MonoBehaviour {

// Use this for initialization

void Start () {

}

// Update is called once per frame

void Update () {

}

/// <summary>

/// 每次游戏对象发生碰撞都执行都执行此方法

/// </summary>

/// <param name="co">可以获得被碰撞的游戏对象</param>

void OnCollisionEnter(Collision co)

{

co.gameObject.renderer.material.color = Color.blue;

}

}

unity3d如何进行碰撞检测

unity3d如何进行碰撞检测

10、测试

unity3d如何进行碰撞检测

unity3d如何进行碰撞检测

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢