Question by
Shilola98 · Apr 17, 2016 at 05:22 PM ·
c#rotationraycastingrotate objectquaternion.lookrotation
Object doesn't rotate well with camera raycasting.
Hi, I'm a beginner in unity and I'm working on my first project after doing a few tutorial projects like Space Shooter, Tanks! etc.
I have a tower with a turret on it and I want to move - rotate - the turret along the X,Y(around the Z axis) plane with raycasting from the main camera. My LayerMask("Screen") is the quad I used as the background.
The code:
using UnityEngine;
using System.Collections;
public class TurretRotation : MonoBehaviour
{
private Rigidbody rb;
private int screenMask;
private float camRayLength = 100f;
void Awake ()
{
rb = GetComponent<Rigidbody>();
//sets the background as the layer for raycasting
screenMask = LayerMask.GetMask("Screen");
}
void FixedUpdate ()
{
Aim();
}
void Aim()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit screenHit;
if (Physics.Raycast(camRay, out screenHit, camRayLength, screenMask))
{
Vector3 turretToMouse = screenHit.point - transform.position;
turretToMouse.z = 0.0f;
//in order to use a vector 3 for rotation, it must be converted to a quaternion
Quaternion newRotation = Quaternion.LookRotation(turretToMouse);
rb.MoveRotation(newRotation);
}
}
}
When I test it and point the mouse over the screen the turret is either facing the camera or facing the background.
prtscr.png
(58.5 kB)
prtscr2.png
(163.4 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612075026im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotating Two Axes for Gravity,Rotating only two axes towards Object 0 Answers
Simple Rotate Script won't work! 2 Answers
How to apply script to a imported OBJ file in unity? 0 Answers
how to get object rotation? 1 Answer
Character Rotation 0 Answers