【问题标题】:How do I make Rigidbody2D.MovePosition move a gameobject in local space?如何让 Rigidbody2D.MovePosition 在本地空间中移动游戏对象?
【发布时间】:2022-01-15 13:14:11
【问题描述】:
我找到了一种方法来查找标题中关于 Rigidbody 而不是 Rigidbody2D 的内容,因为原始方法涉及使用 Transform.TransformDirection(),它仅在 Vector3 上起作用,而 Rigidbody2D.MovePosition 在 Vector2 上起作用。我基本上需要一颗子弹才能向前移动,还有两颗子弹向前移动,但以 45 度角差旋转。
我该怎么做呢?
【问题讨论】:
标签:
c#
unity3d
rotation
rigid-bodies
【解决方案1】:
我假设您有一个子弹预制件,并且您一次实例化 3 个子弹,但希望其中 2 个分别位于 -45 度和 45 度。
//bullet 是你拥有的任何预制件
var bl = Instantiate(bullet);
var bl = Instantiate(bullet);
bl.transform.rotation = //Set rotation here to 45 deg
var bl = Instantiate(bullet);
bl.transform.rotation = //Set rotation here to -45 deg
【解决方案2】:
你的问题让我想起了我前段时间为 game jam 做的一个游戏,所以我检查了代码,似乎我使用了Quaternion.AngleAxis 来旋转子弹。
我假设您有一个要克隆的预制件的引用(在本例中,它是 projectilePrefab),以及一个代表您要拍摄的位置和旋转的 firePoint 变换中间的弹丸。
// Middle Bullet
GameObject mBullet = Instantiate(projectilePrefab, firePoint.position, firePoint.rotation);
var mRb = mBullet.GetComponent<Rigidbody2D>();
middleRb.AddForce(mRb.transform.up * velocity, ForceMode2D.Impulse);
// Left Bullet
GameObject lBullet = Instantiate(projectilePrefab, firePoint.position, firePoint.rotation);
// Rotate here
lBullet.transform.up = Quaternion.AngleAxis(-45, Vector3.forward) * firePoint.transform.up;
var lRb = lBullet.GetComponent<Rigidbody2D>();
lRb.AddForce(lBullet.transform.up * velocity, ForceMode2D.Impulse);
// Right Bullet
GameObject rBullet = Instantiate(projectilePrefab, firePoint.position, firePoint.rotation);
// Rotate here
rBullet.transform.up = Quaternion.AngleAxis(45, Vector3.forward) * firePoint.transform.up;
var lRb = lBullet.GetComponent<Rigidbody2D>();
lRb.AddForce(lBullet.transform.up * velocity, ForceMode2D.Impulse);
如果您在使用此代码时遇到任何问题,请告诉我,我现在无法对其进行测试。
【解决方案3】:
在Vector2 和Vector3 之间存在implicit conversion 和vise versa。这两种类型都可以或多或少地使用可交换的,这将创建一个Vector3,其中z 只是0,或者只使用x 和y 创建一个Vector2,而忽略z。
您可以简单地将Vector3 作为参数传递给Rigidbody2D.MovePosition,它会隐式将其转换为Vector2,而忽略Z 组件。