- Home /
Inconsistent AddForce with raycasting
Hi, I am currently trying to find a solution to my problem but just can't seem to get it right. What I want to happen is when the raycast collides with the ground, the player is launched toward a direction based on the angle of the collider/ground.
My issue is that the AddFroce does not seem consistent in always bringing the player to a certain height, and will sometimes shoot the player high into the air and other times not at all. Here is my code to do this:
private void Update()
{
RaycastHit2D hit = Physics2D.Raycast(raycastStartPoint.position, -Vector2.right, 0.001f);
if (hit.collider != null)
{
if (hit.collider.name == "Ground" || hit.collider.name == "LeftWall" || hit.collider.name == "RightWall")
{
if (shouldAddForce == true)
{
direction = -hit.point; // Find the point of collision
shouldAddForce = false; // Does not allow for antoher collision
StartCoroutine(AllowAnotherShield()); // Calls to end no more collisions
objectRigidbody.velocity = Vector2.zero; // Stops the player's velocity so add
// force does not have to counter the
// current velocity
}
}
}
if(shouldAddForce == false) // If we should be adding force
{
AddForce();
}
}
private void AddForce()
{
objectRigidbody.AddRelativeForce(direction * force); /// Adds force at direction
}
private IEnumerator AllowAnotherShield()
{
yield return new WaitForSeconds(seconds); // Waits for seconds
shouldAddForce = true; // We can find another collision
}
}
Here is a youtube video on what my game looks like and you can see sometimes the player flies way high and other times it does not: https://www.youtube.com/watch?v=cjQuYr8Af6U&feature=youtu.be
Physics operations should happen within FixedUpdate()
. Try changing your update function to FixedUpdate (which shouldn't be an issue as you don't have any inputs being captured here) and see the the problem persists.
Also, is your shouldAddForce
check backwards at the bottom?
Answer by seandolan · Feb 27, 2018 at 04:51 AM
I could watch that video all day. It was so addictive. You could try this instead:
objectRigidbody.AddForce(objectRigidbody.transform.TransformDirection(direction) * force,ForceMode.Impulse);
If this doesn't work, try swapping around the ForceMode to one of the other options.