0
\$\begingroup\$

I'm working on a game with an entity firing a shot. This shot could destroy other entities as well as the entity who generated the shot. My first step was to apply a force to the rigidbody2D of the shot, but when my entity is too fast the shot destroy it (the speed does not match).

I tried adding the speed to the force but the values mismatch by far (the force is a vector of like 150 magnitude, whereas the speed as a magnitude of 1).

I wonder how one can achieve this, to add the current speed of the entity to the shot fired, and i wonder if there's any litterature concerning the way physics is actually handled in Unity, i find very little documentation on the Physics.

Thanks.

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

For a one-off change of velocity, I'd recommend changing velocity yourself. So rather than applying a force to the object, try something like rigidbody2D.velocity += shooter.velocity after you create the shot and figure out the regular shooting velocity.

Secondly, it'd probably be best not to count on the speed difference to avoid the shooter being destroyed by its own bullet. When you create the shot, you could use Physics2D.IgnoreCollision to make it impossible for the shot to hit the entity that created it. If you do need the shot to hit its creator (such as with a ricochet), you could use the same function to let them hit each other again after the shot has already travelled a certain distance.

Let me know if any of that is unclear :)

\$\endgroup\$
3
  • \$\begingroup\$ That was my first idea, but thought it would be a dirty hack. I'm wondering, if I do add the speed this way, will the bullet stay consistant with the physics model? Because the bullet does not only destroy, it could actually push some specific entities also (weird i know but hey...), and i read here and there than bypassing the physics model was not a good idea... \$\endgroup\$
    – Linio
    Commented Apr 18, 2015 at 7:44
  • 1
    \$\begingroup\$ Don't worry, it's not a dirty hack :) Basically, you know how fast and in what direction the bullet should start off. So make it go that fast and in that direction. Acceleration = Force / Mass is all that's happening internally when you apply a force, and acceleration is just a change in velocity. So don't be shy about directly changing velocity for an instantaneous effect. If the intended change is continuous over time, however, then you've gotta be more careful and rely on AddForce() if you're not certain you have the maths covered. \$\endgroup\$
    – Jibb Smart
    Commented Apr 18, 2015 at 8:44
  • \$\begingroup\$ Thanks!! This helped. I'm actually going to use this in other parts too. \$\endgroup\$
    – Linio
    Commented Apr 19, 2015 at 9:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .