0
votes

I have the following script

public class SpeedUp : MonoBehaviour {

    public Rigidbody2D ball;

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.tag == "Ball") {
            ball.AddForce(Vector2.left * 1000f);
            Debug.Log("ABC");
        }

    }

}

and every time I run my game, the Debug.Log("ABC") prints ABC in the console, but the Rigidbody doesn't move, it stays as it is. Can someone explain me why, because I don't understand why does the console print work and the Rigidbody doesn't move

This is the code for the Ball

public class Ball : MonoBehaviour {

    public Rigidbody2D rb;
    public Rigidbody2D hook;
    public float releaseTime = 0.15f;

    private bool isPressed = false;

    void Update()
    {
        if (isPressed)
        {

            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            if (Vector3.Distance(mousePos, hook.position) > 2.5f)
            {
                rb.position = hook.position + (mousePos - hook.position).normalized * 2.5f;
            }
            else
            {
                rb.position = mousePos;
            }
        }
    }

    void OnMouseDown()
    {
        isPressed = true;
        rb.isKinematic = true;
    }

    void OnMouseUp()
    {
        isPressed = false;
        rb.isKinematic = false;
        StartCoroutine(Release());
    }

    IEnumerator Release()
    {
        yield return new WaitForSeconds(releaseTime);
        GetComponent<SpringJoint2D>().enabled = false;
        this.enabled = false;
    }
}
1
Is the Rigidbody marked as kinematic? Can you show us a screenshot of its settings? - Serlite
@Serlite the ball is kinematic when the mouse doesn't touch it, but in order to reach the collider, the ball must be pulled with the mouse and it becomes dynamic as soon as it is touched - Edward
There is no issue with the code itself - your problem either lies in how the ball's rigidbody is set up, or the interaction with the mouse and the ball that you are describing. - ryeMoss
@ryemoss I added the code from the ball script - Edward
If the ball is being dragged into the collider, OnTriggerEnter will happen before isKinematic becomes false (when you release the mouse) and the Force will be applied to the object while it is still kinematic. Is this the case? - ryeMoss

1 Answers

0
votes

The Rigidbody doesn't move may be it's need to getComponenrt()

So, add void Start() method in your the script

public class SpeedUp : MonoBehaviour {

public Rigidbody2D ball;

void Start()
{
   ball = ball.GetComponent<Rigidbody2D>();
}

void OnTriggerEnter2D(Collider2D col)
{
    if (col.tag == "Ball") {
        ball.AddForce(Vector2.left * 1000f);
        Debug.Log("ABC");
    }

}

}