首页 > 解决方案 > Unity2D推拉不同形状的物体

问题描述

您好,我的脚本有问题,玩家只能推动一个完美的方形物体。我添加了这个L 形的对象,我试图通过获取对撞机的侧面来增加拉力,但它不起作用,该对象有 2 个 boxcolliders。因为当玩家将它推到 L 的中心时它是一个 L 形,如果走向错误的方向,因为我的代码是基于玩家位置的大小和可推动的对象

这是我的可推送对象代码

public class PushableObject : MonoBehaviour {

[SerializeField] private Player player;
[SerializeField] private float speed = 2;
[SerializeField] private float distanceX = 2;
[SerializeField] private float distanceY = 2;
[SerializeField] List<PushableObject> objectsInArea = new List<PushableObject>();

private bool isPlayerColliding = false;
private bool isMoving = false;


public bool IsMoving
{
    get { return isMoving; }
}

private void FixedUpdate()
{
    if (isPlayerColliding && player.IsInteractingObject && isAnyOtherObjectMoving())
    {
        move();
        isMoving = true;
    }
    else if(Input.GetKeyUp(KeyCode.E))
        isMoving = false;
}

private void move()
{
    Vector2 direction = transform.position - player.transform.position;

    float x = Mathf.Abs(direction.x), y = Mathf.Abs(direction.y);

    direction.x = x > y ? direction.x : 0;
    direction.y = y > x ? direction.y : 0;

    Vector2 targetPos = new Vector2(transform.position.x, transform.position.y) + direction;

    transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
}

private bool isAnyOtherObjectMoving()
{
    foreach(PushableObject po in objectsInArea)
    {
        if (po.IsMoving)
            return false;
    }

    return true;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.gameObject.CompareTag("Player"))
    {
        isPlayerColliding = true;
    }

}

private void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        isPlayerColliding = false;
    }
}

}

标签: c#unity3d

解决方案


推荐阅读