- Home /
Sucking a zero-gravity ship into a black hole.
Hey,
So I'm making a 2D zero-gravity space game and I have all of the ship's controls etc working. The ship uses AddRelativeForce to move currently.
I have a mesh that I need to pull the player towards. Obviously, they will already be moving through space. I have the trigger all set up, I'm just trying to work out the code to bring the player in. I want them to use the AddRelativeForce to fight the pull of the blackhole and escape.
I tried using Vector2.MoveTowards, but it wasn't really working how I'd like. I found a line online that seemed to do the job when set up:
sh.rb.AddForce((ship.transform.position - transform.position).normalized * pullAmount);
This has the opposite effect but works smoothly. It pushes the player away from the black hole, regardless of where I enter the trigger from. I assume I just need to flip the equation I think. I've tried:
ship position - black hole position normalized * pullamount.
black hole position normalized * pullamount - ship position.
making the pullamount a -pullamount
black hole position normalized / pullamount - ship position.
It seems like everything I'm trying to flip the equation is just either breaking it having the same effect.
Does anyone have any ideas either how to flip this math so it'll pull instead or push OR another solution to bring the moving ship in with physics and allow the player to use their relative force to push away from it?
Thanks in advance!
Can you post a little more code? What is the "sh" gameobject and how is it different from the "ship" gameobject?
Answer by icehex · May 01, 2020 at 05:16 PM
Try:
sh.rb.AddForce((transform.position - ship.transform.position).normalized * pullAmount);
Also be careful with what "sh" is and what "ship" is. I'd guess they should be the same object for this to work.
Nice! Thank you Icehex.
I knew it'd be something small with the math.
For clarity, ship is the GameObject ref and SH is the script on it, which already had a reference to the rigidbody in it for some other stuff. I could have used either as they're on the same transform but I can see how that's confusing without context.
Thanks again!
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
How to check if my enemy hits the ground at a certain velocity then add explosive force. 1 Answer
Object jumps right after the attached HingeJoint2D is Enabled 0 Answers
Debug a rigidbody2d velocity on an exact point 1 Answer
New Pointer Effector 2D Help 0 Answers