我似乎找不到找到使播放器与应该停止播放器的对象碰撞的方法。例如,当我将播放器移到一堵树的墙壁上时,它会像穿过幽灵般在它们之间移动(并稍微偏离网格对齐反弹)。
以下是我所使用的有关Player动作的代码:
using System.Collections;
using UnityEngine;
public class PlayerMovement : Character {
Direction currentDir;
Vector2 input;
bool IsMoving = false;
Vector3 startpos;
Vector3 endpos;
float t;
public Sprite upsprite;
public Sprite rightsprite;
public Sprite downsprite;
public Sprite leftsprite;
public float walkSpeed = 3f;
public bool isAllowedToMove = true;
private Rigidbody2D myRB;
void Start()
{
isAllowedToMove = true;
myRB = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
protected override void Update () {
if (! IsMoving && isAllowedToMove) {
input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (Mathf.Abs(input.x) > Mathf.Abs(input.y))
input.y = 0;
else
input.x = 0;
if (input != Vector2.zero) {
if (input.x < 0) {
currentDir = Direction.Left;
}
if (input.x > 0) {
currentDir = Direction.Right;
}
if (input.y < 0) {
currentDir = Direction.Down;
}
if (input.y > 0) {
currentDir = Direction.Up;
}
switch (currentDir) {
case Direction.Up:
gameObject.GetComponent<SpriteRenderer>().sprite = upsprite;
break;
case Direction.Right:
gameObject.GetComponent<SpriteRenderer>().sprite = rightsprite;
break;
case Direction.Down:
gameObject.GetComponent<SpriteRenderer>().sprite = downsprite;
break;
case Direction.Left:
gameObject.GetComponent<SpriteRenderer>().sprite = leftsprite;
break;
}
StartCoroutine (Move (transform));
}
myRB.velocity = new Vector2 (Input.GetAxisRaw ("Horizontal") * walkSpeed, myRB.velocity.y);
myRB.velocity = new Vector2 (myRB.velocity.x, Input.GetAxisRaw ("Vertical") * walkSpeed);
if (Input.GetAxisRaw ("Horizontal") < 0.5f && Input.GetAxisRaw ("Horizontal") > -0.5f)
{
myRB.velocity = new Vector2 (0f, myRB.velocity.y);
}
if (Input.GetAxisRaw ("Vertical") < 0.5f && Input.GetAxisRaw ("Vertical") > -0.5f)
{
myRB.velocity = new Vector2(myRB.velocity.y, 0f);
}
}
base.Update ();
}
public IEnumerator Move(Transform entity)
{
IsMoving = true;
startpos = entity.position;
t = 0;
endpos = new Vector3(startpos.x + System.Math.Sign(input.x), startpos.y + System.Math.Sign(input.y), startpos.z);
while(t < 1f)
{
t += Time.deltaTime * walkSpeed;
entity.position = Vector3.Lerp(startpos, endpos, t);
yield return null;
}
IsMoving = false;
yield return 0;
}
}
enum Direction
{
Up,
Right,
Down,
Left
}
要注意的其他事情是,我确保使用Rigidbody2D和Box Collider2D组件,并且确保将播放器的Gravity scale设置为0,并冻结了Z轴的旋转。此外,尽管预先安装的tilemap资产是创建2d游戏世界的不错选择,但我确实使用Tiled和Tiled2Unity扩展来创建您在游戏中看到的图块。
请原谅我,如果它看起来太长,但是我似乎无法弄清冲突检测的问题所在。有人可以帮忙吗?