对于固定步数运动(“跳跃”),您需要代码逻辑来确定某个运动是否可行。我建议为目标(红色对象)创建一个类,该类具有一个说明哪一侧打开的变量和一个查看您是否可以从您所在的一侧进入的函数。
在你的移动中你需要检查这样一个物体是否在你想要移动的方向上,并询问它是否可以从你所在的一侧进入。
这是相当伪的,因为我不知道你的网格实现以及你如何确定东西在哪里并且可能会被优化。
public class Player : MonoBehaviour
{
void Update()
{
if("move to left" && "object on left".GetComponent<RedObject>().canEnterFromSide("right") == true)
{
//move
}
else if("move to right" && "object on right".GetComponent<RedObject>().canEnterFromSide("left") == true)
{
//move
}
else if("move to top" && "object on top".GetComponent<RedObject>().canEnterFromSide("bottom") == true)
{
//move
}
else if("move to bottom" && "object on bottom".GetComponent<RedObject>().canEnterFromSide("top") == true)
{
//move
}
}
}
然后在对象上放置一个脚本(或者如果它已经有脚本,则将其添加到它的脚本中)。
public class RedObject : MonoBehaviour
{
// use e.g. "left", "right", "top", "bottom" to specify the open side
// if you spawn the objects, set this upon spawning and according to the orientation obviously
public string openSide = "left";
public bool canEnterFromSide(string side)
{
return side == openSide;
}
}
更新:
好的,我查看了您的项目。目前,您还没有放置障碍物的部分。这应该是您的下一步。
创建一个生成器,它将在您的网格上生成障碍物一个位置(网格间隔将是您的玩家速度。有一个列表或字典,其中包含对您放置的所有障碍物的引用,以便您可以参考它们。一种简单的方法会是这样的:
public class Generator : MonoBehaviour
{
public GameObject obstaclePrefab;
Dictionary<string, GameObject> obstacles; // Dictionary requires using System.Collections.Generic;
// default rotation = open to the left
Dictionary<string, Quaternion> rotations;
void Start()
{
rotations = new Dictionary<string, Quaternion>()
{
{ "left", Quaternion.Euler(0,0,0) },
{ "bottom", Quaternion.Euler(0,90,0) },
{ "right", Quaternion.Euler(0,180,0) },
{ "top", Quaternion.Euler(0,270,0) }
}
}
void SpawnObstacle(Vector2 position, string openSide)
{
GameObject go = (GameObject)Instantiate(obstaclePrefab, position, rotations[openSide]);
go.GetComponent<Obstacle>().openSide = openSide;
string pos = position.x + "_" + position.y;
obstacles.Add(pos, go);
}
GameObject GetObjectAt(Vector3 position)
{
string pos = position.x + "_" + position.y;
if(obstacles.ContainsKey(pos) == true)
{
return obstacles[pos];
}
return null;
}
}
现在,如果您移动,请询问该班级是否在所需目的地有障碍物。 (我省略了这节课的其他内容。)
公共类 PlayerMove : MonoBehaviour
{
公共 int 步;
Generator generator;
void Start()
{
generator = GameObject.FindWithTag("Generator");
}
void Update()
{
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
GameObject go = generator.GetObjectAt(transform.position - new Vector3(step, 0, 0));
if(go == null || go.GetComponent<Obstacle>().CanEnterFromSide("right") == true)
{
transform.position = transform.position - new Vector3(step, 0, 0);
}
}
// repeat for the other three directions.
}
}
现在,这使用了一个固定的象棋网格,其中障碍物占据一个单元格。您的视频显示了其他一些行为,因此这可能对您没有太大帮助。最简单的方法可能是让玩家以平滑的动作移动并使用像 Programmer 展示的碰撞器和刚体,或者像这样使用固定网格。