- Home /
Vector3.MoveTowards moving away from target position
Hi, I have an issue with MoveTowards actually moving away from the target and I don't understand why this is happening. I have a player object (Self) that uses Raycast to get the GrapplingPosition (hit.point) to get a position on a terrain. When I use the following code, the Self object starts moving away from the GrapplingPosition instead of moving toward it. I have attached my Debug.log code below to show what is going on. I tried to use the same code toward random directions and they all do the same move away behavior. Can someone help explaining why this is happening?
Self.transform.position = Vector3.MoveTowards(Self.transform.position, GrapplingPosition, PullSpeed * Time.deltaTime);
Distance = Vector3.Distance(Self.transform.position, GrapplingPosition);
Debug.Log("Self: " + Self.transform.position + ", Distance: " + Distance + ", Target: " + GrapplingPosition);
Self: (491.5, 136.0, 202.7), Distance: 29.96443, Target: (464.7, 140.6, 215.2)
UnityEngine.Debug:Log(Object)
GrapplingHook:Update() (at Assets/Scripts/GrapplingHook.cs:52)
Self: (491.7, 136.0, 202.6), Distance: 30.12826, Target: (464.7, 140.6, 215.2)
UnityEngine.Debug:Log(Object)
GrapplingHook:Update() (at Assets/Scripts/GrapplingHook.cs:52)
Self: (491.8, 136.0, 202.6), Distance: 30.27597, Target: (464.7, 140.6, 215.2)
UnityEngine.Debug:Log(Object)
GrapplingHook:Update() (at Assets/Scripts/GrapplingHook.cs:52)
Update with additional information: Hi, I just want to add a little bit more information. If I use a negative PullSpeed then this code works fine toward to position I point with my Raycast. What I don't understand is why it needs to be a negative in this case. I also tried to do a DrawRay and it is connecting the two positions correctly.
Do this as a test: Run the script and get the logs, then pause the game. In the scene place a sphere object, then take the logs "Target position" and apply it to the sphere. It should move the sphere to where the GrapplingPosition is. Is the sphere where the player grappled?
I suspect, the grappling position isn't where you think it is. Thus the move towards is going the wrong way.
Do you have visual confirmation that the Self is actually moving away? The distance could be reportedly going up because of your terrain traversal (going up a hill in the direction of the target could still increase distance, if it's steep). I'm willing to bet this is collision/rigidbody related.
Use Gizmos to draw a line from your Self gameobject to the GrapplingPosition, I think your RaycastHit point isn't where you think it is.