0
votes

I have an object tagged "Bouncy object" that pushes my player on collision; it works but after collision, my player is like being dragged back to the object tagged "Bouncy object", then does the same thing again like a cycle. The code I used is:

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Bouncy object")
        GetComponent<Rigidbody2D>().AddForce(transform.right * 38, ForceMode2D.Impulse);
}

I then set the drag on the player's Rigidbody to: 1.49. How would I stop this from happening? What I want is for the object tagged "Bouncy object" to push my player on collision (trigger) then freeze Rigidbody2D for like 2 seconds, then allows me to control my player.

1

1 Answers

0
votes

Here is the code you want. I tested just now.

If Cube collide with Block, it bounce to back 0.1 sec and freeze 1 sec.

The key is '-GetComponent ().velocity'.

Here is the screenshot of editor.

public class PlayerController : MonoBehaviour {

public float force = 10f;

float speed = 5f;
float freezeTime = 1f;

bool isCollide = false;

void FixedUpdate () 
{
    float dirX = Input.GetAxis ("Horizontal");
    float dirY = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector2 (dirX, dirY);

    if(isCollide==false)
        GetComponent<Rigidbody2D> ().velocity = movement * speed;
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Boundary") {
        isCollide = true;
        GetComponent<Rigidbody2D> ().AddForce (-GetComponent<Rigidbody2D> ().velocity * force, ForceMode2D.Impulse);
        Invoke("StartFreeze", 0.1f);

    }
}

void StartFreeze()
{
    GetComponent<Rigidbody2D> ().constraints = RigidbodyConstraints2D.FreezeAll;
    Invoke("ExitFreeze", freezeTime);
}

void ExitFreeze()
{
    GetComponent<Rigidbody2D> ().constraints = RigidbodyConstraints2D.None;
    isCollide = false;
}
}