0
\$\begingroup\$

I have a cursor object (simple quad) that I'm moving around above a floor mesh. The floor mesh has varying heights (hills and such).

How can I set my quad to sit at the same angle as the mesh floor?

I'm using a raycast to cast down on the position of the cursor and get the angle of the floor mesh using hit.normal, then reflect.

RaycastHit hit;
var rayStart = new Vector3(transform.position.x, transform.position.y + 5f, transform.position.z);
if (Physics.Raycast(rayStart, Vector3.down, out hit, 10f)) {
    if (hit.collider.tag == "Floor") {
        Vector3 incomingVec = hit.point - rayStart;
        Vector3 reflectVec = Vector3.Reflect(incomingVec, hit.normal);
        cursorSprite.transform.eulerAngles = reflectVec;
        }
    }

(I've left out the position code, that works, its just the angle code that doesnt)

I've tried a bunch of variations, altering the reflectVec angle x, y and z but I can't figure out how to get it correct :/

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

This code is meaningless:

Vector3 incomingVec = hit.point - rayStart;
Vector3 reflectVec = Vector3.Reflect(incomingVec, hit.normal);
cursorSprite.transform.eulerAngles = reflectVec;

There is no particular relationship between the orientation you want, and the reflection of the incident ray by the hit normal. There is no relationship at all between a direction vector in cartesian coordinates and Euler angles in degrees - the units don't even match.

It looks like you want something more like this:

cursorSprite.transform.rotation = Quaternion.LookRotation(-hit.normal, Camera.main.transform.up);

This points the "forward" vector of your sprite (its local z+ axis) down into the ground, perpendicular to its surface, so the object's local xy plane sits parallel to the surface. It tries to align the object's local y+ axis toward the camera's up axis. This works for sprites and quads which by default are made to be viewed from their z- side.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you! Angles confuse me.... \$\endgroup\$
    – Muckington
    Jun 26, 2020 at 16:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .