Hello. I’m at a roadblock in my code trying to find a way to make a moving circle collider reflect off the walls in a linear fashion, similar to pong. After much research and help, I’ve found a good way to reflect the collider, but not a perfect way to detect the collision point. This code functions well if the collision point is accurate, but often times it isn’t. I believe this is due to an unpredicted result from my raycast. I was wondering if anyone had a suggestion that could remove these unexpected results?
Some notes: My speed gets set from an exterior script. The trajectory is an angle converted to a Vector2, it’s definitely accurate as well.
public class sword : MonoBehaviour {
public Rigidbody2D rb;
public CircleCollider2D coll;
private float spin;
public float speed;
public Vector2 trajectory;
public GameObject Player;
Animator anim;
RaycastHit2D hit;
// Use this for initialization
void Start () {
speed = 0.0f;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "player" && speed <= 1)
{
transform.position = new Vector2(-1000, -1000);
Player.GetComponent<movement>().equipped = true;
}
if (collision.tag == "solid")
{
hit = Physics2D.Raycast(transform.position, trajectory);
trajectory = Vector2.Reflect(trajectory, hit.normal);
}
}
private void FixedUpdate()
{
//constantly calculating new velocity
rb.velocity = speed * trajectory;
speed = speed * 0.93f; //drag
}
}