我试图通过随机地左右/前进来让角色四处走动,大多数情况下,角色都会这样做,但他们每隔一段时间就会穿过墙壁,我不希望这种情况发生。你能在我的代码中看到我遗漏了什么吗?
墙壁上有对撞机,圆圈也是,但是圆圈对撞机只是一个触发器,因为我想让圆圈能够互相穿透,而不是穿过墙壁。
这似乎是一个人物的转变,并有一段时间再次转向墙。
下面是一个视频示例:https://www.youtube.com/watch?v=ZOfGn3bsuLA
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(Rigidbody2D))]
public class Character : MonoBehaviour {
public float speed;
protected Transform frontRaycast, leftRaycast, rightRaycast;
protected List<int> lastPossibleDirs = new List<int>();
protected int lastDir;
protected bool changed = false;
protected bool forward, left, right;
// Use this for initialization
void Awake () {
frontRaycast = transform.FindChild("FrontRaycast").transform;
leftRaycast = transform.FindChild("LeftRaycast").transform;
rightRaycast = transform.FindChild("RightRaycast").transform;
}
void Update(){
// Test for a wall in front and on sides
forward = Physics2D.Linecast(transform.position, frontRaycast.position, 1 << LayerMask.NameToLayer("Wall"));
left = Physics2D.Linecast(transform.position, leftRaycast.position, 1 << LayerMask.NameToLayer("Wall"));
right = Physics2D.Linecast(transform.position, rightRaycast.position, 1 << LayerMask.NameToLayer("Wall"));
// Add each direction to the list of possible turns
List<int> possibleDirs = new List<int>();
if(!forward){
possibleDirs.Add(0);
}
if(!left){
possibleDirs.Add(1);
}
if(!right){
possibleDirs.Add(2);
}
int dir = 0;
if(possibleDirs.Count > 0){
dir = (int)possibleDirs[Random.Range(0, possibleDirs.Count)];
}
if(changed){
// Move forward with left or right option
if(lastPossibleDirs.Exists(element => element == 0) && lastPossibleDirs.Exists(element => element > 0) && (left || right) && lastDir == 0){
changed = false;
}
// Left
else if(lastPossibleDirs.Exists(element => element == 1) && left && lastDir == 1){
changed = false;
}
// Right
else if(lastPossibleDirs.Exists(element => element == 2) && right && lastDir == 2){
changed = false;
}
}else{
switch(dir){
case 0:
if(!left || !right){
transform.Rotate(new Vector3(0,0,0));
changed = true;
}
break;
case 1:
transform.Rotate(new Vector3(0,0,90));
changed = true;
break;
case 2:
transform.Rotate(new Vector3(0,0,-90));
changed = true;
break;
}
lastDir = dir;
lastPossibleDirs = possibleDirs;
}
transform.Translate(Vector2.right * Time.deltaTime * speed);
}
}以下是字符上检测区域所在位置的屏幕截图

发布于 2014-08-22 20:27:44
我要做的第一件事就是取消你圆圈上的触发器并利用
Physics2d.IgnoreLayerCollision(circle layer)在Awake()中
https://stackoverflow.com/questions/25454577
复制相似问题