- Home /
Adding force relative to the distance from an object
So im building a game with small planets that have push and pull features (think super mario galaxy except 2.5D).
I have it so that there is a Forcemode.Force applied to the player when they come in contact with the trigger collider which is roughly double the size of the object itself. The force works fine but i would like to complicate things a bit more and make it so the closer the player comes to the pushing planet the more force that is applied to the player and the further away they are then the less. Example; if he jumps really close to the object then a strong force is applied but if he barely skims the trigger collider area then it only applies a weak force.
I was originally thinking along the lines of calculating the distance between the player and the object and multiplying the force accordingly but obviously I cant multiply a force by a Vector3. I was wondering if this could be calculated through raycasting? Any help would be highly appreciated.
Thanks in advance
Answer by cbjunior · Jun 26, 2017 at 12:23 PM
Actually, you can multiply a force by a Vector3, because in Unity a force is represented by a Vector3. Try something like this:
float forceMult = maxDistance - Vector3.distance (planet.transform.position, transform.position);
if (forceMult > 0)
rigidbody.AddForce (Quaternion.LookRotation (planet.transform.position - transform.position).eulerAngles * forceMult, ForceMode.Acceleration);
Thanks for the answer. Would you be able to explain what's actually happening in the code you provided me? I have a hard time understanding quaternions and Euler angles
Quaternion and EulerAngles are just two ways of representing rotations in three dimensional space. Theyre like Vector3s, except for rotation ins$$anonymous$$d of position. In the first line of the code, we're finding the distance from the planet using the built in Vector3.Distance function to find the distance between the two bodies as a float. We're then subtracting this from a max distance to find our multiplier. If we're within the max distance (multiplier greater than zero) we apply the force to the player object in the direction that faces the planet by finding the direction using Quaternion.LookRotation. We have to take the EulerAngles Angles version because EulerAngles Angles are already in a Vector3 format that we can pass to the Addforce function, which can't directly take Quaternion as an argument.
Your answer
Follow this Question
Related Questions
Smooth Movement on Geometry Collission? 0 Answers
Enemy line of sight using linecast and colliders 1 Answer
Moving objects using raycasting? 1 Answer
Using two trigger colliders 1 Answer
Trigger not working 2D 1 Answer