- Home /
Stop Dashing through walls
Hey guys. I'm working on a sidescrolling platformer and I have a GameObject with a box collider and a rigid body that I want to dash to a desired location using the following code -
while(Vector3.Distance(Vector3.Distance(transform.position, targetLocation) > 0.1 && timeOfDash < 1)
{
timeOfDash += Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position,targetLocation,Time.deltaTime*dashSpeed);
yield return null;
}
Everything seems to be working fine until it comes down to collision. If my Object is to dash to a location and is blocked by the wall, it looks as if the floor and the code are fighting with eachother, throwing my game object back and forth (clipping through the wall), until my dash times out (timeOfDash >= 1 ) and the floor is throwing my object upwards.
Is there a way to get perfect collision (so nothing can ever clip through, no matter the code)? Or maybe Vector3.MoveTowards is a bad solution to my problem?
Please advice.
Answer by jaskij · Sep 06, 2012 at 01:29 PM
Do not move the object by means of moving the transform. Instead, modify the speed of the rigidbody (that should be done in the FixedUpdate() method inherited from MonoBehaviour). Preferably by using Rigidbody.Addforce(), although modifying the speed vector directly is also possible should you want to do so (look into Vector3 Rigidboy.velocity).
Ah yes! Haven't tried that out yet, but it sounds like the correct solution. Adjusting a "Speed modifier" does sound like a much cleaner way than moving the transform directly. I'll check it out and tick you up when I'm done :)