我正在制作 PacMan 类型的游戏,只是为了好玩,但我遇到了一个问题。我已经创建了一个角色并用瓷砖地图制作了一张地图。我将 tilemap collider 2d 添加到 tilemap 和 box collider 2d 以及角色的刚体(运动学)。这是我的移动代码:
public class PlayerController : MonoBehaviour
{
[SerializeField]
private float _speed = 3.0f;
private Vector2 _direction = Vector2.zero;
private void Start()
{
}
private void Update()
{
Move();
CheckInput();
}
private void CheckInput()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
_direction = Vector2.left;
} else if (Input.GetKeyDown(KeyCode.RightArrow))
{
_direction = Vector2.right;
} else if (Input.GetKeyDown(KeyCode.UpArrow))
{
_direction = Vector2.up;
} else if (Input.GetKeyDown(KeyCode.DownArrow))
{
_direction = Vector2.down;
}
}
private void Move()
{
transform.localPosition += (Vector3)(_direction * _speed) * Time.deltaTime;
}
}
我已经更改了“联系人对模式”,但它不起作用。这是我的问题的照片: collision problem
答案 0 :(得分:1)
运动学刚体不允许碰撞。它们旨在用于墙壁和事物。最好使用动态 Rigidbody2D,并禁用重力和任何其他您不想要的力。
动态刚体是您可以在下拉菜单中选择而不是运动学的其他内容之一。将其设置为动态非常重要,因为动态允许对对象施加力。
此外,在使用刚体时,您不希望使用变换移动它。
我会以速度移动它,以便检测碰撞。
Rigidbody2D rb;
private void Start()
{
rub = GetComponent<Rigidbody2D>();
}
private void Update()
{
Move();
CheckInput();
}
private void CheckInput()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
_direction = Vector2.left;
} else if (Input.GetKeyDown(KeyCode.RightArrow))
{
_direction = Vector2.right;
} else if (Input.GetKeyDown(KeyCode.UpArrow))
{
_direction = Vector2.up;
} else if (Input.GetKeyDown(KeyCode.DownArrow))
{
_direction = Vector2.down;
}
}
private void Move()
{
rb.velocity = _direction * _speed * Time.deltaTime;
//set all of the drag variables on the Rigidbody
//to very high, so it slows down when they stop moving.
}