S
S
Sarcasop2019-10-31 00:33:39
Game development
Sarcasop, 2019-10-31 00:33:39

How to make a normal ricochet?

The bottom line is that I need to implement a ball ricochet. I want to do it without the help of Rigidbody. I'm trying to do it now through Raycast. The ricochet really turns out, but in the event that I release the ball from the coordinates (0, y), y is any. If x is different from zero, then the ricochet goes along a trajectory that is not clear to me. What can you advise? Below is a piece of code with the ricochet itself.

if (Input.GetKey(KeyCode.Space))
        {
            _direction = transform.up;
        }

        transform.Translate(transform.TransformDirection(_direction) * Time.deltaTime * _speed);
        LayerMask _mask = LayerMask.GetMask("Wall");
        if (Physics2D.Raycast(transform.position, _direction, .5f, _mask))
        {
            GameObject _tempo;
            _tempo = Instantiate(_forInstantiate, transform.position, _forInstantiate.transform.rotation); //_forInstantiate необходим для определения перпендикуляра для метода Reflect
            _direction = transform.TransformDirection(Vector2.Reflect(transform.position, _tempo.transform.right).normalized);
            Destroy(_tempo.gameObject, .1f);
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sarcasop, 2019-10-31
@Sarcasop

Understood the question. If anyone is interested in the solution - everything is trivially simple, I read the help incorrectly, which is why I incorrectly wrote the arguments in Vector2.Reflect().

transform.Translate(_direction * Time.deltaTime * _speed);
        LayerMask _mask = LayerMask.GetMask("Wall");
        RaycastHit2D hit = Physics2D.Raycast(transform.position, _direction, .5f, _mask);
        if (hit && isActive)
        {
            _direction = Vector2.Reflect(_direction, hit.normal).normalized;  
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question