I want to set the X component of an object’s scale equal to the X scale of the normal below the object. Take a look:
The white shiny thing should reach from track barrier to the other [it’s a cube].
I thought I should use a raycast to get the underlying normal and then just use the localSize, but does it return the size of the normal [Quad shaped] or the size of the collider normal [triangle] and how can I achieve to have the X size spawning from the left track barrier to the right track barrier?
The code below leads to the result seen in the picture above:
Ray rayFlash = new Ray(new Vector3(flashTransform.position.x, flashTransform.position.y + 2f, flashTransform.position.z), Vector3.down);
RaycastHit hitInfoFlash;
Transform flashTransform;
if (Physics.Raycast(rayFlash, out hitInfoFlash, 4f, 1 << LayerMask.NameToLayer("Track")))
{
flashTransform.localScale = new Vector3(hitInfoFlash.normal.normalized.x, flashTransform.localScale.y, flashTransform.localScale.z);
}
Instead of getting the ground normal, I check for the distance to the left and the right border with Rays, position the Flash Object in the center and scale it upwards to match the sum of both distances. This requires two Rays instead of one but I hope this is ok since the Rays are only used once at startup.
rayFlashRight = new Ray(flashTransform.position, flashTransform.right);
rayFlashLeft = new Ray(flashTransform.position, -flashTransform.right);
if (Physics.Raycast(rayFlashRight, out hitInfoFlashRight, 25f, 1 << LayerMask.NameToLayer("Obstacle")))
{
if (Physics.Raycast(rayFlashLeft, out hitInfoFlashLeft, 25f, 1 << LayerMask.NameToLayer("Obstacle")))
{
flashTransform.localScale += new Vector3(hitInfoFlashRight.distance + hitInfoFlashLeft.distance, flashTransform.localScale.y, flashTransform.localScale.z);
if (hitInfoFlashRight.distance > hitInfoFlashLeft.distance)
{
flashTransform.position = flashTransform.position + flashTransform.right * (hitInfoFlashLeft.distance - ((hitInfoFlashLeft.distance + hitInfoFlashRight.distance) / 2f));
}
else
{
flashTransform.position = flashTransform.position - flashTransform.right * (hitInfoFlashLeft.distance - ((hitInfoFlashLeft.distance + hitInfoFlashRight.distance) / 2f));
}
}
}