Home > Back-end >  How do I make Rigidbody2D.MovePosition move a gameobject in local space?
How do I make Rigidbody2D.MovePosition move a gameobject in local space?

Time:12-11

I found a way to find what the title says for Rigidbody but not for Rigidbody2D, since the original method involves using Transform.TransformDirection(), which only functions on Vector3 while Rigidbody2D.MovePosition functions on Vector2. I essentially need a bullet to move forward, with two more bullets moving forward but rotated at a 45 degree angle difference.

How would i go about doing this?

CodePudding user response:

Your question reminded me of a game I made for a game jam a while ago so I checked the code, and it seems I used Quaternion.AngleAxis to rotate the bullets.

I'm assuming you have a reference to the prefab you want to clone (in this example, it's projectilePrefab), as well as a firePoint Transform that represents the position you want to shoot from and the rotation of the middle projectile.

// 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);

Let me know if you run into any issues with this code, I can't test it right now.

CodePudding user response:

I'm assuming you have a bullet prefab, and that you are instantiating 3 bullets at once, but want 2 of them to be at -45 and 45 degrees respectively.

//bullet is whatever prefab you have

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
  • Related