unity3d立方体碰撞检测(c#代码实现)
由于unity自带的碰撞组件特别耗费性能,网上的unity物体碰撞的c#代码实现比较少,没有适合的,只能自己写一个来用:
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Assets
{
class Class1 : MonoBehaviour
{
List<Action> listAction = new List<Action>();
//用来检测碰撞的间隔时间(可以直接把检测放入update()中,不过100毫秒的定时器效果上也能实现)
System.Timers.Timer timer = new System.Timers.Timer();
//原坐标
Vector3 oldPoint;
//要移动的坐标
Vector3 point;
//0:待机;1:移动
int currentState = 0;
//是否可以移动
bool canMove = true;
// Use this for initialization
void Start()
{
oldPoint = transform.position;
timer.Interval = 100;
timer.Enabled = true;
timer.Elapsed += (a, b) => isMove(point);
}
// Update is called once per frame
void Update()
{
foreach (Action a in listAction) {
a();
}
listAction.Clear();
point = transform.position;
if (currentState == 1) {
if (checkCollision()) {
canMove = false;
}
}
}
void isMove(Vector3 position) {
if (oldPoint != position)
{
if (!canMove)
{
listAction.Add(new Action(()=> gameObject.transform.position = oldPoint));
canMove = true;
}
else {
currentState = 1;
oldPoint = position;
}
}
else {
currentState = 0;
}
}
bool checkCollision() {
Vector3 zzPoint = gameObject.transform.position;
Vector3 zzScale = gameObject.transform.localScale;
//另一物体坐标信息
GameObject dm = GameObject.Find("Cube (1)");
Vector3 dmPoint = dm.transform.position;
Vector3 dmScale = dm.transform.localScale;
//坐标检测(当两个物体的x、y、z方向间距都小于两个物体在该方向上的长度)
if ((Math.Abs(zzPoint.x - dmPoint.x) <= zzScale.x / 2 + dmScale.x / 2) &&
(Math.Abs(zzPoint.y - dmPoint.y) <= zzScale.y / 2 + dmScale.y / 2) &&
(Math.Abs(zzPoint.z - dmPoint.z) <= zzScale.z / 2 + dmScale.z / 2))
{
return true;
}
return false;
}
}
}