简体   繁体   English

如何找到用于字符冲突的旋转矩形的新中心? Unity2D

[英]How do I find the new center of a rotated rectangle for character collision? Unity2D

I have been programming a myriad of character animations with changing colliders for a 2D Unity game, but am having trouble figuring out how to find the new center of a rotated rectangle for a prone animation. 我已经为2D Unity游戏编写了许多具有变化的碰撞器的角色动画,但是在弄清楚如何为俯卧动画找到旋转矩形的新中心时遇到了麻烦。 Rotating the rectangle isn't an issue, as I've simply set the current length of the rectangle as its new width, and vice versa. 旋转矩形不是问题,因为我仅将矩形的当前长度设置为其新宽度,反之亦然。 The problem is that my new rectangle falls to the ground because its center (or "offset," as Unity calls it) is the same as the default collider; 问题是我的新矩形掉到了地面上,因为它的中心(或Unity所说的“偏移”)与默认的对撞机相同; it's briefly in the air when I press my prone button. 当我按下俯卧按钮时,它短暂地在空中。

Basically, I want the following to happen in my game: 基本上,我希望游戏中发生以下情况:

  1. My character stands upright with his default rectangle collider, which collides with the ground due to gravity. 我的角色使用默认的矩形对撞机直立,该对撞机由于重力而与地面碰撞。

  2. I press a button, and the rectangle is reassigned values so that it appears to be rotated 90 degrees, but its new center makes it so that my character remains touching the ground the entire time. 我按下一个按钮,并重新分配了矩形值,使其看起来好像旋转了90度,但是它的新中心使它得以始终使我的角色接触地面。

Here's a graphic that hopefully explains things better: https://imgur.com/d9BaJ9R 这是一个希望可以更好地说明问题的图形: https : //imgur.com/d9BaJ9R

I was able to program a crouch animation using similar logic, but cannot wrap my head around how to apply it to this scenario. 我能够使用类似的逻辑对蹲伏动画进行编程,但无法将注意力应用于如何将其应用于这种情况。 Here's that successful piece of code: 这是成功的代码:

    boxCollider.size = new Vector2(boxCollider.size.x, boxCollider.size.y * .5f);
    boxCollider.offset = new Vector2(boxCollider.offset.x, boxCollider.offset.y - (boxCollider.size.y * .5f));

Do you need this? 你需要这个吗?

exchange dimensions: 交换尺寸:

boxCollider.size = new Vector2(boxCollider.size.y, boxCollider.size.x); 

set new center height as half-height of new rectangle (staying x the same): 将新的中心高度设置为新矩形的一半高度(保持x不变):

 boxCollider.offset = new Vector2(boxCollider.offset.x, boxCollider.size.y * .5f);

Thanks MBo for helping me rethink this a bit. 感谢MBo帮助我重新考虑了这一点。 The answer is actually very similar to the code I posted earlier. 答案实际上与我之前发布的代码非常相似。

    boxCollider.size = new Vector2(boxCollider.size.y, boxCollider.size.x);
    boxCollider.offset = new Vector2(boxCollider.offset.x, boxCollider.offset.y - (boxCollider.size.y * .5f));

This sets the new rectangle center correctly, and of course can be easily reversed when the player stands up again. 这样可以正确设置新的矩形中心,当然,当播放器再次站立时,可以很容易地将其反转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM