- Home /
Question by
alexjamescooper88 · Apr 07, 2020 at 09:48 PM ·
rotationraycasthitfps controller
How do you make a Raycast follow your mouse in an FPS?
I tried to add the mouse controls into the rotation of the raycast, but it say that a field initializer cannot reference the non-static field, method, or property. Here is my script: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MouseControl : MonoBehaviour {
public float MouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
float yRotation = 0f;
private Ray ray;
// "hit" variable stores information.
private RaycastHit hit;
// drawing vector's direction.
[SerializeField]
private Vector3 direction = new Vector3(xRotation, yRotation, 0f);
// distance of vector.
[SerializeField]
private float distance = 10f;
// using offsetY for ignoring gameObject itself. If you do not want to offset the ray, you can use layerMask as Physics.Raycast method's 4th parameter.
[SerializeField]
private float offsetZ = 0.6f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
ray = new Ray(new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z + offsetZ), direction);
}
void Update()
{
// gameObject's position is changing over time.
ray.origin = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z + offsetZ);
if (Physics.Raycast(ray, out hit, distance))
{
Debug.Log(hit.collider.gameObject.name, hit.collider.gameObject);
}
// Draw ray for visualition.
Debug.DrawRay(ray.origin, ray.direction * distance, Color.green, 1f);
float mouseX = Input.GetAxis("Mouse X") * MouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * MouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
yRotation -= mouseX;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, -yRotation, 0f);
}
}
Comment
Your answer
Follow this Question
Related Questions
How to rotate FPSController in mobile? 1 Answer
How can I rotate, I can't rotate fully? 0 Answers
Scaling a rotated object in global Y 1 Answer
FPS Controller rotation,FPS Controller rotation problem 0 Answers
Keep the scene view rotation of my camera in play mode (it resets to 0) [EXAM ^^] 1 Answer