Hello, I’ve been trying to figure out how rotate two objects towards the players mouse/camera rotation.
Specifically I have a Cannon that needs to rotate on the Y and X axis. Whilst the Base only needs to Rotate on the Y Axis. I can’t for the life of me seem to figure out how to constrain the two either as they’re designed to stop after X amount of degree’s
This is what I had so far.
public class CannonAim : MonoBehaviour
{
[SerializeField]
private Transform cannonBarrel;
[SerializeField]
private Transform cannonStand;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
cannonBarrel.transform.rotation = Camera.main.transform.rotation;
cannonStand.transform.rotation = Camera.main.transform.rotation;
//Ray rayOrigin = Camera.main.ScreenPointToRay(Input.mousePosition);
//RaycastHit hitInfo;
//Physics.Raycast(rayOrigin, out hitInfo);
//Vector3 direction = hitInfo.point - cannonBarrel.position;
//cannonBarrel.rotation = Quaternion.LookRotation(direction);
}
}
public class CannonInteract : MonoBehaviour, Iinteract
{
[SerializeField]
bool PlayerNear;//Player inside the trigger
[SerializeField]
bool Interacting;//Player is using Cannon
[SerializeField]
CharacterController CharCon; //Characters Controller
[SerializeField]
GameObject CharObj;//Character game object
[SerializeField]
Transform CharTran;//get the transform of the character to return the camera on Exit.
[SerializeField]
GameObject CamPosObj; //Parent for the camera to lock to
[SerializeField]
Transform CamPos; //position for the camera to reference
void Start()
{
GetComponent<CannonAim>().enabled = false;
CamPos = CamPosObj.transform;
}
private void OnTriggerEnter(Collider collider)
{
PlayerNear = true;
CharCon = collider.GetComponent<CharacterController>();//the Players Character Controller on Collider
CharObj = CharCon.gameObject;//gets the Characters gameobject from the Character Controller on Collider
CharTran = CharObj.transform;//gets the Characters Transform from the Character Object
}
private void OnTriggerExit(Collider collider)
{
GetComponent<CannonAim>().enabled = false;
PlayerNear = false;
}
public void Iinteracted()
{
Interacting = !Interacting;// Flip Bool
if (Interacting && PlayerNear)
{
Camera.main.transform.position = CamPosObj.transform.position;
Camera.main.transform.SetParent(CamPos);
GetComponent<CannonAim>().enabled = true;
CharCon.enabled = false;//Lock the players position
Debug.Log("Controller enabled");
}
else if (!Interacting)
{
Camera.main.transform.position = CharCon.transform.position;
Camera.main.transform.SetParent(CharTran);
GetComponent<CannonAim>().enabled = false;//stop cannon aiming
CharCon.enabled = true;// return the player movement
Debug.Log("Controller disabled");
}
}
}