Hi every, first time poster here.
I have the following code to make a simple 2D Ball (circle) bounce around some colliders on a scene, without using any RigidBody (Unity’s Physics are a bit of an overkill for what I need).
void FixedUpdate()
{
Vector2 pos;
Vector2 prev_pos;
Vector3 rot;
pos = transform.position;
speed.y -= gravity;
if(!was_hit)
{
float ray_length = speed.magnitude;
Vector2 dir = speed.normalized;
Vector2 prev_dir = Vector2.zero;
RaycastHit2D hit = Physics2D.CircleCast(
pos,
radius,
dir,
ray_length,
collision_mask
);
if(hit.collider != null)
{
bool on_going;
float bounced;
float perm;
on_going = true;
bounced = 1;
while(on_going)
{
prev_dir = dir;
prev_pos = pos;
perm = 2.0f * Vector2.Dot(dir, hit.normal);
dir = dir - (hit.normal * perm);
print (
(hit.point + (hit.normal * radius))
+ " :: " +
hit.centroid
);
//pos = (hit.point + (hit.normal * radius));
pos = hit.centroid;
ray_length *= (1 - hit.fraction) * bounce;
bounced *= bounce;
if(ray_length > 0)
{
hit = Physics2D.CircleCast(
pos,
radius,
dir,
ray_length,
collision_mask
);
if(hit.collider == null)
on_going = false;
}
else
on_going = false;
}
rotation = Vector2.Angle(prev_dir * -1, dir) * speed.magnitude;
pos = pos + (dir * ray_length);
speed = dir * (speed.magnitude * bounced);
}
else
{
pos = pos + speed;
}
transform.position = new Vector3(pos.x, pos.y, transform.position.z);
}
was_hit = false;
rot = transform.localEulerAngles;
rot.z += rotation * Time.deltaTime;
transform.localEulerAngles = rot;
}
My problem is that the line 46 [pos = hit.centroid] causes this for no apparent reason.
The weird part is that if I uncomment the line 45 [pos = (hit.point + (hit.normal * radius))] above, the code works perfectly.
The even weirdest thing of it all is that the comment above those 2 lines prints the exact same value for both (when the working code runs, since I don’t know how to get prints under infinite loops).
Any ideas why this is happening?
This is not exactly a critical matter, since I already have a solution, but it is one of those things that simply bugs me.
Why wasting calculations, when the thing is already done?
Also, it would make the code simpler because I need to relocate it to make it a function used more than once per frame, and with more complex uses.