- Home /
How do you make a projectile move in an arc? (2d)
void makeBullet1(GameObject bulletType, float xPos, float yPos, float angle, float speed)
{
Vector2 position = new Vector2(xPos,yPos);
Quaternion rotation = Quaternion.Euler(0,0,angle);
GameObject bullet = Instantiate(bulletType, position, rotation);
//EnemyBullet bulletScript = bullet.GetComponent<EnemyBullet>();
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.velocity = transform.TransformDirection(bullet.transform.up) * speed;
}
So the code above is what I use to create a "bullet", it creates a gameobject in the position you choose at the angle and speed you put in, but this only makes a bullet go straight. I am trying to make a bullet go in a U pattern, so I created the following script and attached it to the special bullet.
public Rigidbody2D rb;
void Start()
{
StartCoroutine(rotateStyle());
}
IEnumerator rotateStyle()
{
for(int i = 0; i < 180; i++)
{
transform.Rotate(0,0,1);
//rb.velocity = transform.TransformDirection(transform.up); (option 1)
//rb.velocity = transform.forward; (option 2)
yield return new WaitForSeconds(0.01f);
}
}
At first I tried to only update the rotation which worked but the bullet kept moving at its initial direction, so I tried adding those two lines I commented out. Option 1 made it do some weird things and option 2 made the bullet stay in place. Does anyone know how to make the bullet go forward or is there a better way to do this?
Answer by JesseAtBlue · Aug 18, 2020 at 08:37 PM
Hi @sonicerik3,
I think you almost had it right! My solution would be to rotate the velocity vector as you did rotate the bullet itself. I think it didn't work in your case because when you rotate an object the velocity vector is not included. So i think something like this (not tested):
for(int i = 0; i < 180; i++) { Vector2 vel = rb.velocity; rb.velocity = Quaternion.Euler(0, 0, i) * vel; yield return new WaitForSeconds(0.01f); } }
Thanks for the help, there's no way I would have figured this out by myself
After a bit of testing, this ended up being the final result:
IEnumerator rotateStyle()
{
Vector2 vel = rb.velocity;
for(int i = 0; i < 180; i++)
{
transform.Rotate(0,0,1);
rb.velocity = Quaternion.Euler(0, 0, i) * vel;
yield return new WaitForSeconds(0.01f);
}
}
Your answer
Follow this Question
Related Questions
C# Projectile Ricochet After Collision2d 1 Answer
Deteriorating force on object? 0 Answers
How to calculate projectile range 2 Answers
unity2d change angular direction 1 Answer