- Home /
Pulling in another object
I'm making a 2D game where the player moves on the x-axis and y-axis and you're looking at the level down the z-axis. I want to make it so the player can use a button to pull powerups to them if they're within a close enough distance.
Looking around, I think I have to use AddForce in some way, but I couldn't figure it out for the life of me. Any help would be greatly appreciated as always.
Answer by Loius · Oct 02, 2010 at 04:43 PM
Use the distance between the two objects as the speed of movement:
var pullSpeedFactor : float = 1.0; // Higher values make objects home in faster
// later...
if ( Input.GetKey( HomingKey ) ) {
var diff : Vector3 = player.transform.position - targetObject.transform.position;
targetObject.transform.position += diff / diff.magnitude * pullSpeedFactor;
}
Using that, the farther away an object is, the slower it should move towards the player. If you need physics movement, instead of teleportation, use targetObject.rigidbody.AddForce( that stuff ) instead. Might need to greatly increase pullSpeedFactor, depending on the mass of your powerups.
ins$$anonymous$$d of diff / diff.magnitude
I guess you could have used diff.normalized
Your answer
Follow this Question
Related Questions
Deteriorating force on object? 0 Answers
Throwing a gameObject based on distance (2D) 0 Answers
Enemy AI 2D not working? ( Rigidbody.Addforce() ) 2 Answers
Enemy shoot at player in 2D game 3 Answers
pulling in objects one end, and releasing out the other 0 Answers