- Home /
Problem with reflect
I made a ball that reflects when it hits a wall or an object (cylinder). I also made a sign for the direction of movement and reflection with the LineRenderer. When the ball hits the wall, the direction of reflection is exactly the same as the direction indicated by the line render, but when it hits the cylinder object, the direction of reflection is not the same as the direction indicated by the LineRenderer. I think maybe the problem is with the cylinder NORMALS. Can anyone help?
private void Reflection(Vector3 direction)
{
ray = new Ray(transform.position, direction);
lineRenderer.positionCount = 1;
lineRenderer.SetPosition(0, transform.position);
float remainingLenght = lineRendererLength;
for (int i = 0; i < reflectionCount; i++)
{
if (Physics.Raycast(ray.origin, ray.direction, out hit, remainingLenght, mirrorLayer))
{
lineRenderer.positionCount += 1;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, hit.point);
remainingLenght -= Vector3.Distance(ray.origin, hit.point);
ray = new Ray(hit.point, Vector3.Reflect(ray.direction, hit.normal));
}
else
{
lineRenderer.positionCount += 1;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, ray.origin + ray.direction * remainingLenght);
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.layer == 9)
{
ContactPoint contact = collision.GetContact(0);
touchReleaseDirection = Vector3.Reflect(touchReleaseDirection, contact.normal);
}
}
The main reason this would occur is because the collision doesn't actually occur at the position the previewing Raycast hits the surface.
Why not?
Well, it's because your ball has volume, where the Raycast does not. If you move your ball to a distance of radius
away from the point of intersection of the Raycast at ANY non-perpendicular angle, you will find that the ball will already be intersecting the surface!
Unfortunately, this doesn't solve the problem, because the solution is actually much more complicated based on the shapes of objects colliding with eachother (even simple ones), but I hope this at least clarifies why your results aren't what you're expecting.
Your answer
Follow this Question
Related Questions
Create a sine wave(using line renderer) and reflect it from colliders 0 Answers
Call Update once per object vs Update all in a central script 2 Answers
Trouble with fieldInfo.SetValue() and arrays 1 Answer
Is it possible to rotate the environment's reflection source at runtime? (C#) 1 Answer
ExecutionEngineException: Attempting to JIT compile method 0 Answers