Home > Enterprise >  Making an object shake when player collides
Making an object shake when player collides

Time:11-18

I am trying to build a 3D game in Unity and in this game I want an object to wobble/shake when the player collides with it.

I can do it in 2D but I do not know how to convert it to 3D.

This is my code:

using System.Collections;
using UnityEngine;

public class ItemNudge : MonoBehaviour
{
    private WaitForSeconds pause;
    private bool isAnimating = false;

    private void Awake()
    {
        pause = new WaitForSeconds(0.04f);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (isAnimating == false)
        {
            if (gameObject.transform.position.x < collision.gameObject.transform.position.x)
            {
                StartCoroutine(RotateAntiClock());
            }
            else
            {
                StartCoroutine(RotateClock());
            }

            //Play rustle sound if player

        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (isAnimating == false)
        {
            if (gameObject.transform.position.x > collision.gameObject.transform.position.x)
            {
                StartCoroutine(RotateAntiClock());
            }
            else
            {
                StartCoroutine(RotateClock());
            }

            //Play rustle sound if player

        }
    }

    private IEnumerator RotateAntiClock()
    {
        isAnimating = true;

        for (int i = 0; i < 4; i  )
        {
            gameObject.transform.Rotate(0f, 0f, 2f);

            yield return pause;
        }

        for (int i = 0; i < 5; i  )
        {
            gameObject.transform.Rotate(0f, 0f, -2f);

            yield return pause;
        }

        gameObject.transform.Rotate(0f, 0f, 2f);

        yield return pause;

        isAnimating = false;
    }

    private IEnumerator RotateClock()
    {
        isAnimating = true;

        for (int i = 0; i < 4; i  )
        {
            gameObject.transform.Rotate(0f, 0f, -2f);

            yield return pause;
        }

        for (int i = 0; i < 5; i  )
        {
            gameObject.transform.Rotate(0f, 0f, 2f);

            yield return pause;
        }

        gameObject.transform.Rotate(0f, 0f, -2f);

        yield return pause;

        isAnimating = false;
    }
}

CodePudding user response:

Change this:

OnTriggerEnter2D(Collider2D collision)..
OnTriggerExit2D(Collider2D collision)...

To this:

OnTriggerEnter(Collider collision)..
OnTriggerExit(Collider collision)...

And make sure the Colliders on the 3D objects aren't collider 2d, but instead regular colliders.

  • Related