- Home /
Question by
dragonking300 · May 01, 2017 at 07:08 PM ·
c#scripting problem
How do you keep rotation constant no matter where you look?
I want my sword model to rotate and look the same no matter where i'm facing but I don't know how to add that. Help?(I'd also accept links to other answers or just links to this concept because I can't seem to find the answer with google)
using UnityEngine;
using System.Collections;
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseCameraScript : MonoBehaviour
{
CursorLockMode lockerd = CursorLockMode.Locked;
void Start()
{
Cursor.lockState = lockerd;
}
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
float rotationY = 0F;
public float length;
public Vector3 SwordPos;
public Transform Sword;
void Update()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(transform.position, Camera.main.transform.forward * length, Color.black);
SwordPos = ray.origin + (ray.direction * length);
SwordPos = ray.GetPoint(length);
Sword.position = SwordPos;
Debug.Log(ray.direction);
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
}
}
Comment
Best Answer
Answer by tMahon · May 01, 2017 at 09:40 PM
So you're trying to keep the sword in view like a First Person weapon correct? The simplest thing to do is put it where it looks nice and make it a child object to the main camera so as the main camera rotates it translates the object to stay in view.
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do i script basic attack animation? 3 Answers
How do I delay an Ad? 2 Answers
Use a enum from another script 2 Answers