0
\$\begingroup\$

I have been trying to change the gravity scale of my Rigidbody2d when I click on it. By default it is by 0 and when I click on it, it should change to 1, so that it falls down. I have a square with a boxcollider2d and a Rigidbody2d and a square with just a box collider.

public bool gravity = false;
public bool m_isRunning = false;
public SpriteRenderer m_spriteRenderer;
private Rigidbody2D rb;

private void Update()
{
    if (gravity)
    {
        rb.gravityScale *= -1;
    }
}

private void Start()
{
    m_spriteRenderer = this.GetComponent<SpriteRenderer>();
    rb = GetComponent<Rigidbody2D>();
}

private IEnumerator Changecolor()
{
    yield return new WaitForSeconds(1);
    int random = Random.Range(1, 4);

    if (random == 1)
    {
        m_spriteRenderer.color = Color.blue;
    }
    else if (random == 2)
    {
        m_spriteRenderer.color = Color.red;
    }
    else if (random == 3)
    {
        m_spriteRenderer.color = Color.green;
    }
    else
    {
        m_spriteRenderer.color = Color.yellow;
    }

    this.StartCoroutine("Changecolor", 3f);
}

private void OnMouseDown()
{
    gravity = true;
    m_isRunning = !m_isRunning;

    if (m_isRunning)
    {
        StartCoroutine("Changecolor", 3f);
    }
    else
    {
        StopCoroutine("Changecolor");
    }
}
\$\endgroup\$
1
\$\begingroup\$

This line, from inside your code's update method:

rb.gravityScale *= -1;

is setting gravity scale to current gravity scale times -1. Since you have set gravity scale to start as 0 this highlighted statement is evaluating to gravity scale 0 times -1. So ultimately the gravity scale is being repeatedly set to 0.

Changing that line to:

rb.gravityScale = 1;

This code will now directly set gravity scale to one and you should see the object fall.

\$\endgroup\$
0
\$\begingroup\$

if you have no need to toggle the gravity back off you can simply replace the line in OnMouseDown() bool gravity = true; with rb.gravityScale = 1; and remove the gravity bool and the if(gravity) check in the Update method.

public bool m_isRunning = false;
public SpriteRenderer m_spriteRenderer;
private Rigidbody2D rb;


private void Start()
{

    m_spriteRenderer = this.GetComponent<SpriteRenderer>();
    rb = GetComponent<Rigidbody2D>();
}


private void OnMouseDown()
{
     rb.gravityScale = 1;

    m_isRunning = !m_isRunning;

    if (m_isRunning)
    {
        StartCoroutine("Changecolor", 3f);
    }
    else
    {
        StopCoroutine("Changecolor");
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy