Hi everyone again!
I have a strange rotation problem with raycast. (If you want, to examine the error, I have attached a very small video of the problem).
Basically depending on where I aim with the raycast the object rotates or not! I can’t understand why or if I’m wrong. I’ve a collider attach to object that works with the filtered raycast. I repeat everything works, but according to the point where it hits the beam
I use two scripts: One for the object to rotate, and another for the Player interact. With the player
Object Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
public class RotateObject : MonoBehaviour
{
public GameObject obj;
[Space]
public float rotSpeed = 100f;
public float distanceFromCamera = .8f;
[Space]
public GameObject player;
private Vector3 objPos;
private Quaternion objRot;
private Vector3 nv;
private float rotX;
private float rotY;
//Camera
private Camera m_MainCamera;
private Vector3 CenterCamera;
private void Awake()
{
Vector3 eulerAngles = transform.eulerAngles;
rotX = eulerAngles.x;
rotY = eulerAngles.y;
}
private void Start()
{
obj = this.gameObject;
//store position and rotation of object
objPos = obj.transform.position;
objRot = obj.transform.rotation;
m_MainCamera = Camera.main;
}
public void CC()
{
player.GetComponent<FirstPersonController>().enabled = false;
CenterCamera = m_MainCamera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, distanceFromCamera));
obj.transform.position = CenterCamera;
}
public void OnMouseDrag()
{
rotX = Input.GetAxis("Mouse X") * rotSpeed * Mathf.Deg2Rad;
rotY = Input.GetAxis("Mouse Y") * rotSpeed * Mathf.Deg2Rad;
obj.transform.Rotate(Vector3.up, -rotX, Space.World);
obj.transform.Rotate(Vector3.right, rotY, Space.World);
obj.transform.Translate(rotSpeed * nv.normalized * Time.deltaTime);
}
public void ResetObj()
{
obj.transform.position = objPos;
obj.transform.rotation = objRot;
}
}
Part of Player script:
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, InteractDistance, maskLayer))
{
Debug.DrawLine(ray.origin, hit.point, Color.red);
if (checkImpact == false)
{
if (crosshair != null && hit.collider.CompareTag("InteractableObj"))
{
crosshair.enabled = true;
}
}
if (Input.GetMouseButtonDown(0) && clickLeft)
{
///--- MORE CODE HERE --- ///
if (hit.collider.gameObject.name == "painting")
{
isClickRightActive = true;
}
if (isClickRightActive)
{
//reference for script RotateObject
hit.collider.GetComponent<RotateObject>().CC();
hit.collider.GetComponent<RotateObject>().OnMouseDrag();
}
}
}
}
else crosshair.enabled = false;
if (Input.GetMouseButtonDown(1) && isClickRightActive)
{
hit.collider.GetComponent<RotateObject>().ResetObj();
player.GetComponent<FirstPersonController>().enabled = true;
isClickRightActive = false;
}
}
Where do you think I’m wrong? Thanks for any help
6146933–671366–test.zip (1.1 MB)