1
\$\begingroup\$

I am a newbie on coding, wanted to work on a game as practice and started to work on a 2D top view game, and on a barren desert area, I have a Twigball for my player to touch and move it because of its dynamic rigidbody.

This Twigball has 2 animations which those are idle and movement animations. Everytime my player touches, Twigball moves, changes its position. But what I need is: Everytime this Twigball moves by touching or any other ways, I want its "isMoving" bool is "true" and make it start the "movement" animation, everytime it stops, I want to start its "idle" animation.

It might be simple thing but I couldn't find how to do it with code. Rigidbody works good with its options (linear drag, angular drag etc...) on inspector. I have a TwigBallBehaviour script attached to the TwigBall but its empty. OnColliderEnter would work for Player touches etc. but this Twigball will also move itself as behaviour. So I need codes to do all that I think, probably calculating position etc... I have already done all changes in Animator window. But what should I write as code? Any advices?

\$\endgroup\$
1
  • \$\begingroup\$ Sounds like you should show us your TwigBallBehaviour code. \$\endgroup\$
    – DMGregory
    Jun 17, 2021 at 16:36

1 Answer 1

1
\$\begingroup\$

Well I dealt with the problem, here the solution:

I wrote many codes to TwigBallsBehaviour which it was empty before, here the codes I wrote:

public class TwigBallsBehaviour : MonoBehaviour
{

    private Animator anim;
    public Rigidbody2D rb;
    private bool isMoving;
    void Start()
    {
        anim = GetComponent<Animator>();
        rb = this.GetComponent<Rigidbody2D>();
        anim.SetBool("isMoving", false);
    }

    void FixedUpdate()
    {
        if(rb.velocity.x == 0)
        {
            anim.SetBool("isMoving", false);
        }
        else
        {
            anim.SetBool("isMoving", true);
        }

    }

}

I also added a code group to the Player's Script, used simply collisions. You can see below:

private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "TwigBall")
        {
            Debug.Log("Turning");
            if (transform.position.x < collision.gameObject.transform.position.x)
            {
                Debug.Log("From Right");

            }
            else
            {
                collision.gameObject.transform.parent.eulerAngles = new Vector3(0, -180, 0);
                Debug.Log("From Left");
            }

        }
    }

After all these, added collider to TwigBall, tagged it as "TwigBall". This is how I solved my problem.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .