当Unity碰撞检测遇到Character Controller后

Unity Feb 28, 2018 ~

当Unity碰撞检测遇到Character Controller后,会发现Character Controller用不了普通物体Collider的碰撞检测,下面记录这两种方法;

注:文章末尾有视频;

一、Collider

Unity方面

1.首先新建一个胶囊体并命名为Player1,然后挂载一个C#脚本Player1.cs,组件具体看下图和视频

2.注意创建摄像机并调好位置

3.然后再来创建2个Cube,放置到适当的位置,并给其中一个添加一个名为“Move Object”的标签

代码方面
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player1 : MonoBehaviour {

    public float speed = 5;		// 定义移动速度
    private Rigidbody rig;		// 定义Rigidboy组件

	// Use this for initialization
	void Start () {
        rig = this.GetComponent<Rigidbody>();	// 获取Rigidboy组件
	}
	
	// Update is called once per frame
	void Update () {
        float v = Input.GetAxis("Vertical") * speed;	// z轴
        float h = Input.GetAxis("Horizontal") * speed;	// x轴

        rig.velocity = new Vector3(h,0,v);
	}

	// 碰撞检测方法
    void OnCollisionEnter(Collision col)
    {
    	// 如果碰撞到标签名为Move Object的物体就打印一个“HI”
        if(col.gameObject.tag == "Move Object")
        {
            print("HI");
        }
    }
}

二、Character Controller

Unity方面

1.再次创建一个胶囊体并命名为Player2,然后挂载一个C#脚本Player2.cs,其他组件看下图和视频

2.摄像机还是要调好位置;

代码方面
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player2 : MonoBehaviour {

    public float speed = 5;         // 定义并赋值移动速度
    public float gravity = 10;      // 定义并赋值重力
    private CharacterController chara;	// 定义CharacterController组件
    private Vector3 moveV;				// 定义移动

	// Use this for initialization
	void Start () {
        chara = GetComponent<CharacterController>();	// 获取CharacterController组件
	}
	
	// Update is called once per frame
	void Update () {
        float v = Input.GetAxis("Vertical") * speed;	// z轴
        float h = Input.GetAxis("Horizontal") * speed;	// x轴

        if (chara.isGrounded)
        {
            moveV = new Vector3(h, 0, v);
        }
        moveV += Vector3.down * gravity * Time.deltaTime;	// 模拟重力
        chara.Move(moveV * Time.deltaTime);
    }

	// 碰撞检测方法
    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Rigidbody body = hit.collider.attachedRigidbody;
        // 如果有碰撞到物体就打印物体名
        if(body == null || body.isKinematic)
        {
            return;
        }
        else
        {
            Debug.Log("Touch gameObject : " + hit.collider.gameObject.name);

            // 销毁操作
            // Destroy(hit.collider.gameObject);

            // 推动标签为Move Object的物体
            if (hit.collider.gameObject.tag == "Move Object")
            {
                body.velocity = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
            }
        }
    }
}

三、视频

https://www.bilibili.com/video/av20198674/

Tags

Weic Ma

没有什么事是一个脑瓜子解决不了的,要是不行就Remove掉你的脑瓜子吧!

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.