- Home /
Question by
kofficoffee · Sep 17, 2018 at 04:29 AM ·
3daxismousepositiontransform.lookat
How to lock axis for LookAt?
Im using a raycast and LookAt(); to have a plane attached to my character have its z axis looking at the mouse cursor. I want to Lock all the rotations except for the z axis and I cannot figure out how to do it. Does anyone know an answer?
Here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lookatmouse : MonoBehaviour {
private Camera mainCamera;
public float x;
// Use this for initialization
void Start () {
mainCamera = FindObjectOfType<Camera>();
}
// Update is called once per frame
void Update () {
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLength;
if (groundPlane.Raycast(cameraRay, out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue);
transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
transform.rotation.x = 0;
Quaternion.x = 0;
}
}
}
Comment
Answer by tormentoarmagedoom · Sep 17, 2018 at 09:31 AM
Good day.
You only need to set the rotation each frame. For example, If i want to lock X rotation of an object to 30º
rotX = 30;
rotY = Object.transfomr.eulerAngles.y;
rotZ = Object.transfomr.eulerAngles.z;
Object.transfomr.eulerAngles = new Vector3 (rotX, rotY, rotZ(;
Good bye!