and than I use following code to align my object( cube ) with surface’s normal
gameObj.transform.up = interpolatedNormal;
Problem with this is that object rotates around y-axis while I move cursor over mesh and i just want him to be aligned with normal but preserve its rotation around y-axis. How can I achieve this?
Any advice appreciated
As you’ve noticed, setting “up” to a direction doesn’t say which “spin” you should have (known as a degree of freedom.) The lookAt command has an optional 2nd input to account for this – if you don’t add it, the computer assumes you want that free spin to be as “up” as possible.
Using transform.up= doesn’t seem to have a good way to specify that free spin, so the computer accidentally bounces it around on you. You could try aiming it first, to trick “up” into giving a consistant free-spin:
[untested]
transform.LookAt(whereever it should be aimed);
transform.up = theNormal;
I don't like to fight with setting "up", so use this:
// facing is the 0-360 "free" y-spin I want:
transform.rotation = Quaternion.Euler(0,facing,0);
// We are on flat ground, and spun. Now tilt with ground:
// compute tilt rotation:
Quaternion tilt = Quaternion.FromToRotation(Vector3.up, norm);
// apply tilt rotation:
transform.rotation = tilt*transform.rotation;
this will make him look out from the normal, but with his head towards the sky. Some variation of that sounds like what you want, but you may need to further modify it.