Davide Nale
Davide Nale

Reputation: 179

Use transform.LookAt freezing Y rotation?

[EDIT] Solved with:

Vector3 relativePos = hit.point - pivot.transform.position; Vector3 rotation = Quaternion.LookRotation(relativePos).eulerAngles; pivot.transform.localEulerAngles = new Vector3(0, 0, rotation.y);

Hello i recently came across a problem. I'm trying to make this object to look at my raycast point, without having to rotate it. As yu can see from the picture the script is not working properly.

the standard "gun" the "gun" after the transformation

The code I'm using:

Ray ray = theCamera.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
    RaycastHit hit;
    Physics.Raycast(ray, out hit);
    pivot.transform.LookAt(hit.point);
    pivot.transform.rotation = new Quaternion(0, pivot.transform.rotation.y, 0, 0)

The question: Is possible to make the "blue arrow" to look at the "hit.point" remaining in the same rotation plane? Sorry for the bad explanation but i'll post aslo an image of the result I'd like to achieve(the red cube is the raycast point). enter image description here

Upvotes: 2

Views: 1730

Answers (4)

Fahim kamal Ahmed
Fahim kamal Ahmed

Reputation: 255

In my game the enemy will face towards the player but LookRotation() function also changes the x value which I don't want. So I did something like this

var relativePos = thePlayer.transform.position - transform.position;
var rotation = Quaternion.LookRotation(relativePos).eulerAngles;
transform.rotation = Quaternion.Euler(0, rotation.y, 0);

hope it helps someone.

Upvotes: 0

Kokolo
Kokolo

Reputation: 260

If what you need is just to rotate the object around the Y axis, in the direction of the hit.point, without affectin X and Z axis...

... Then in that case, I believe freezing X and Z rotation will do the trick.

You can do that in the inspector, or through code:

Rigidbody _rigidbody = GetComponent<Rigidbody>();
_rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ

This is not mistake, as it uses the bitwise OR operator. Also note that rotation constraints are applied in Local space, not WorldSpace.


EDIT: Deleted first unneeded part, as I didn't understand the question from first try :)

Upvotes: 0

Absinthe
Absinthe

Reputation: 3391

I guess you just want to rotate on Y, not X & Z? In any event you should never modify or create a Quaternion out of parts, use the built in methods:

Vector3 rotation = Quaternion.LookRotation(relativePos).Euler
public Quaternion rotationAdjusted = Quaternion.Euler(0, rotation.eulerAngles.y, 0);
transform.rotation = rotationAdjusted

See Quternion.Euler and Quaternion.eulerAngles

Upvotes: 1

databyss
databyss

Reputation: 6488

Try something like this:

// Keep the Y component the same as your transform
pivot.transform.LookAt(new Vector3(hit.point.x, this.transform.position.y, hit.point.z));

Upvotes: 0

Related Questions