我使用MoveTowards
实现移动系统。我有几个Collider2D
障碍,不应该被我的对象重叠。
void Update()
{
if (playerType == PLAYER_TYPE.PLAYER_ONE)
{
if (Input.GetKey(KeyCode.W))
CheckIfAbleThenMove(gameObject.transform.position + transform.up * speed * Time.deltaTime);
if (Input.GetKey(KeyCode.S))
CheckIfAbleThenMove(gameObject.transform.position + (-1) * transform.up * speed * Time.deltaTime);
if (Input.GetKey(KeyCode.D))
CheckIfAbleThenMove(gameObject.transform.position + transform.right * speed * Time.deltaTime);
if (Input.GetKey(KeyCode.A))
CheckIfAbleThenMove(gameObject.transform.position + (-1) * transform.right * speed * Time.deltaTime);
}
float step = moveTowardsSpeed * Time.deltaTime;
gameObject.transform.position = Vector3.MoveTowards(transform.position, target, step);
}
private void CheckIfAbleThenMove(Vector2 position)
{
Ray ray = new Ray(position, Vector3.zero);
RaycastHit2D hit = Physics2D.GetRayIntersection(ray);
if (hit)
{
if (hit.collider.gameObject.tag == "obstacle")
return;
}
target = position;
}
我无法弄清楚如何仅在特定方向禁用移动,该玩家能够绕过障碍物。