保持CircleCollider2D与精灵Unity对齐

本文关键字:Unity 对齐 精灵 CircleCollider2D 保持 | 更新日期: 2023-09-27 18:12:17

我正在使用Unity中的2D精灵制作2D植物模拟。这些植物被描绘成圆形的精灵。我想做的是增加精灵的半径,并让CircleCollider2D跟随。因为它们有不同的比例,我用的是半径的增量,而不是绝对增量。但问题是,尽管对撞机半径和精灵半径之间的关系保持不变,但对撞机半径的增长速度却快于精灵。

下面是增加大小的代码:

void Grow(GameObject plant)
{
    float currentRadius = plant.GetComponent<CircleCollider2D>().radius;            //Radius of the collider 
    float scaledRadius = Mathf.Max(plant.transform.localScale.x, transform.localScale.y);       //Radius of the sprite
    float radiusIncrease = growthSpeed * Time.deltaTime;
    float procIncrease = (currentRadius + radiusIncrease) / currentRadius;    //The procuental increase of the radius, need for sprite scaling
    plant.GetComponent<CircleCollider2D>().radius *= procIncrease;
    Vector3 oldLocalScale = plant.transform.localScale;
    Vector3 newLocalScale = new Vector3(oldLocalScale.x * procIncrease, oldLocalScale.y * procIncrease, oldLocalScale.z);
    plant.transform.localScale = newLocalScale;
}

保持CircleCollider2D与精灵Unity对齐

我发现CircleCollider2D的半径随着精灵的增加而增加,这意味着我不需要自己改变碰撞器的半径。