Always out of collision

Viewed 37

I have a kind of spikes in my game, where the sphere is "Player" if the player steps on the spikes it should be kicked out of the spikes collider. I'm using for now random range, it works well sometimes, but in some situations, it just comes to the spikes again. What I want is if the ball has collided with spikes it should be bounced away to a random position, but not be able to jump to the position of the spikes again, like a double collision.

    public float ballBounceStrenght;
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.CompareTag("Player"))
        {
            Debug.Log("collision");
            var position = new Vector3(Random.Range(-70, 70.0f), Random.Range(90f, 90.0f), Random.Range(-70.0f, 70.0f));
            ball.AddForce(position * ballBounceStrenght);
        }
    }

This is the code I'm using run for random range. Have no Idea should I do it like that, maybe just fix numbers or there is some other way to do it.

1 Answers

I would use a function to calculate that position, soas to avoid the spikes vertical. You can use polar coordinates in the XZ plane for that, and the return your new pos back in cartesian coords.

Not debugged code, just for your inspiration:

//return new pos from vertical pos aviding a vertical cilinder. 
private Vector3 NewPos(
  (float x, float z) VerticalPos, 
  float radiusToAvoid, float radiusMax) {
  
  float fi = Random.Range(0f, 360f);
  float radiusApart = Random.Range(radiusToAvoid, radiusMax);
  float radomHeight = Random.Range(70,90); //according to your code y range
  
  return new Vector3(VerticalPos.x + radiusApart  * Math.Cos(fi), VerticalPos.z + radiusApart * Math.Sin(fi));
}

Then you would need to pass the x and z to the function:

public float ballBounceStrenght;

private void OnCollisionEnter(Collision collision)
{
    if(collision.gameObject.CompareTag("Player"))
    {
        Debug.Log("collision");
        var position = NewPos((transform.position.x, transform.position.z), 50f, 20f);
        ball.AddForce(position * ballBounceStrenght);
    }
}

All the Vector3 pos can be passed instead of only the x and the z, so that you can also handle the relative y in the NewPos function. However I provided you the sample code that way to leave clear the "pseudo vertical cilinder" of the spikes along all the y (vertical axis) to obtain the new position.

Related