Brick Breaker Movement and Collisions Using Casts?

I can’t seem to get the right type of movement using Rigidbodies so I decided to try handling the collisions with casts and movement with transform.Translate. It seems to be working fine until the collision is above the ball, in this case it just passes right through.

What I’m looking to do with this is have full control over the movespeed of the ball/ no sliding or wierd interactions associated with rigid bodies.

    private IEnumerator HandleMove()
    {
        while (true)
        {
            var overlapHit = Physics2D.OverlapCircle(transform.position, .1f, _hitMask); // Constantly do circle cast around ball
            if (overlapHit)
            {
                Vector2 castDirection = _currentDirection - (Vector2)transform.position; // Current Direction of moving ball
                var hitPoint = Physics2D.Raycast(transform.position, castDirection, 1f, _hitMask); //Raycast To the hit point
                _currentDirection = Vector2.Perpendicular(hitPoint.point - _currentDirection);  //Move Perpendicular to currentDirection/Velocity
            }
            transform.position += (Vector3)_currentDirection.normalized * _speed * Time.deltaTime; //Move the ball
            yield return null;
        }
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        Vector2 inDirection = _currentDirection;
        Vector2 inNormal = collision.contacts[0].normal;
        _currentDirection = Vector2.Reflect(inDirection, inNormal);
    }

Found this and using it in tandem with the coroutine seems to be working well.

Why is this a co-routine? This should just be on a per-frame basis.

Also you’re calculating castDirection based on a (what I assume is a) directional vector and a positional Vector, which is going to give you bung results. Wouldn’t you just cast in _currentDirection, ie the direction it’s heading in?

1 Like

Yeah, if someone is using while (true) and yield return null they should just be using Update. Coroutines make no sense in these cases because it’s just meaningless overhead. You made the code a tiny bit slower for it.

1 Like