Ok I am trying to do what I thought would be a simple bouncing bullet. Bullet hits wall, bounces off like a laser. I have now been at this for six hours. I was found this: Vector3.Reflect - wrong direction - Unity Answers and tried to reverse engineer the code but it is not working correctly for me.
Their Code (adapted for Physics2D):
function drawLaser(startPoint:Vector3,n:int)
{
var hit : RaycastHit2D ;
var rayDir:Vector3 = Spawner.transform.up;
for(var i = 0; i < n; i++)
{
hit = Physics2D.Raycast (startPoint, rayDir, 1000);
if (hit.collider != null)
{
Debug.DrawLine (startPoint, hit.point, Color.red, 0.1, false);
rayDir = Vector3.Reflect( (hit.point - startPoint).normalized, hit.normal ) ;
startPoint = hit.point;
}
}
}
Now the thing that has me really confused is the above code works perfectly fires the little laser and bounces off the walls. But when I try to use the same calculation on my projectile, it derps of whatever which way it feels like. Code for my projectile here:
function OnCollisionEnter2D(coll: Collision2D)
{
if(coll.collider.GetComponent(Health) != null)
{
coll.collider.GetComponent(Health).Hurt(Dammage);
}
if(PingCount <= 0)
{
Destroy(gameObject);
}
else
{
var dir = Vector3.Reflect( (coll.contacts[0].point - transform.position).normalized, coll.contacts[0].normal);
var angle : float = Mathf.Atan2(-dir.x,dir.y) * Mathf.Rad2Deg;
var targetRot = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = targetRot;
}
PingCount -= 1;
}
I would really appreciate it if someone could explain what I am doing wrong. Thanks in advance : )
PS: All of this is using physics2d