1
\$\begingroup\$

This is the code I'm using to make an object bounce across the scene:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class Enemy2 : MonoBehaviour
{
    [SerializeField] private float _speed;
    
    private Rigidbody2D _rb;

    private Vector2 _velocity;

    private void Awake()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    // Start is called before the first frame update
    void Start()
    {
        Vector2 dir = Random.insideUnitCircle;
        if (_rb.velocity.x == 0 && _rb.velocity.y == 0)
            dir = new Vector2(0.5f,0.5f);
        
        _velocity = dir.normalized * _speed;
        _velocity = new Vector2(0, -1);
        _rb.velocity = _velocity;

        FaceDirection();
    }

    private void FixedUpdate()
    {

    }

    // Update is called once per frame
    private void OnCollisionEnter2D(Collision2D other)
    {
        Debug.Log("Collision: "+_rb.velocity);
        _velocity = new Vector2(0, +1);//Vector2.Reflect(_velocity, other.contacts[0].normal);
        _rb.velocity = _velocity;
    }

    private void FaceDirection()
    {
        transform.localScale = new Vector2(Mathf.Sign(_velocity.x),1);
    }
}

I have hardcoded the initial and Reflect directions just to make sure it wasn't my fault and it produces same behaviour: The object gets stuck when colliders with a collider instead of "rebound".

I'm using a dynamic rigid body with trigger set to false and no linear drag.

Can anybody guess what's hapenning here?

\$\endgroup\$
1
\$\begingroup\$

In general you should not set a rigidbody’s velocity directly, as it often results in weird behavior, per the docs:

Rigidbody2D.velocity

Instead, try AddForce(), AddTorque() or AddForceAtPosition()

\$\endgroup\$
4
  • \$\begingroup\$ I tried AddForce before asking, same thing happens. \$\endgroup\$
    – Notbad
    Oct 6 at 22:34
  • \$\begingroup\$ @Notbad hmm ok — can you share a minimal version of your scene set up (hierarchy etc?) \$\endgroup\$ Oct 6 at 22:38
  • 1
    \$\begingroup\$ Well, I found the issue. And it is just embarrasing. I think I was tweaking the character in editor and lost all values when exited and forgot to reset the gravity scale to 0. The velocity version works ok. And I think I will stick with it because in my case makes more sense than ApplyForce. \$\endgroup\$
    – Notbad
    Oct 6 at 22:53
  • 1
    \$\begingroup\$ @Notbad no worries -- often simply asking the question lets you reframe your mindset into seeing the problem through a different lens. Congrats on getting out of this rabbit hole! \$\endgroup\$ Oct 6 at 23:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.