Question by
micheal_s · Mar 02, 2019 at 10:19 PM ·
reflectionvector2raycasthit2dcollisionsreflect
Vector2.Reflect returns opposite reflection
I'm trying to create a ricochet for a 2D game using raycasts to detect and calculate a reflection. But the reflection seems to work only sometimes. please help. heres my code:
public class Projectile : MonoBehaviour
{
[SerializeField] float speed = 3f;
[SerializeField] LayerMask collisionMask;
void Update()
{
}
private void FixedUpdate()
{
transform.Translate(Vector2.up * speed * Time.deltaTime);
Reflect();
}
private void Reflect()
{
Ray2D ray = new Ray2D(transform.position, transform.up);
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, transform.up, Time.deltaTime * speed + 0.5f, collisionMask);
Debug.DrawRay(transform.position, transform.up,Color.blue);
if (hitInfo)
{
Vector2 reflectDir = Vector2.Reflect(ray.direction, hitInfo.normal);
Debug.Log(reflectDir);
Debug.Log(hitInfo.normal);
float rot = 90 - Mathf.Atan2(reflectDir.x, reflectDir.y) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(0, 0, rot);
Debug.Log("gay");
}
}
}
Comment