- Home /
Mistake in Function with Collision and AddForce
Hi people! I'm trying to make this function work and I've spotted an error I can't seem to understand.
What this is supposed to do is to make the head of a rope ( which the player can instantiate) act like a Grappling Hook. The hook itself is labelled with a tag that other objects in my game look for when colliding with something. If the tag matches then a SpringJoint is added to the object and the rope is forced to lock at the first contact point of their collision.
This position's floats are stored in the collFloat variables.
Then, if a button is pressed this function is called, but right now it's not working as expected. The first time a rope locks to a target position everything seems fine. From then on things become odd, to say the least:
First of all the cached position is not changing properly, for some reason it returns the correct value in one frame, then swaps back to the original one just before applying the force
The force is multiplying by itself every time a new position is cached... I really don't know why
So, right now it's working just once. Which is very strange. Please, tell me you've got an idea about why it's doing this!
Here's the code I've wrote so far:
//SO... let's make this very basic
//I'll call this from a KeyInput If and you'll apply force to me so that I can reach the head of the hook.
//But where's the head of the hook?
//Here it is... ideally.
Vector3 hookPosition = new Vector3(collFloatX,collFloatY,collFloatZ);
Debug.Log("collision X = "+collFloatX); <----- THIS IS THE CALL THAT PRINTS DIFFERENT VALUES
//Then I need the direction and distance toward which I'll apply the force ( I suspect it's gonna apply it for 1 frame)
//Vector3 distance = hookPosition-thePlayer.transform.position;
float distance = Vector3.Distance(thePlayer.transform.position,hookPosition);
Vector3 direction = hookPosition-thePlayer.transform.position;
//It IS for just a dozen of frames, but that's good right now because it's enough to start moving
if(distance > 0.5f){
thePlayer.rigidbody.AddForce(direction*10000f);//imagine this as a straight line
//thePlayer.rigidbody.AddForce(Vector3.up*5000f);//Add this and you have an arc.
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to call OnTriggerEnter once 5 Answers
Overlap Detection HELP!! 0 Answers
Detecting whether a player is touching the ground 1 Answer
How to make a death-on-collision script for Air Strike Starter Kit? 1 Answer