For one segment of my game, the player is in a fixed position (no movement) and has to aim and shoot at enemies in a first person 3D perspective using the Mouse. The player is holding a wand that shoots projectiles (which I have working) and I need it to rotate and aim towards the cursor as an aiming reticle. I also want to limit how much the player can rotate, so they can look around, but can't turn more than 180 degrees (sort of like this). However, I'm a designer and am having trouble programming this myself. I haven't been able to find a proper solution.
So far, I've been able to cobble the following code together, but the aiming is super wonky and doesn't properly point to the mouse position, making it impossible to actually aim at anything. I would really appreciate some help with figuring this out.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShoot : MonoBehaviour {
public float magnifier = 0.5f;
public Rigidbody shotPrefab;
public Transform barrelEnd;
public float shotSpeed = 500;
public Rigidbody sparkPrefab;
// Update is called once per frame
void Update () {
Ray mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
float midPoint = (transform.position - Camera.main.transform.position).magnitude * magnifier;
transform.LookAt (mouseRay.origin + mouseRay.direction * midPoint*magnifier);
if (Input.GetButtonDown("Fire1"))
{
Rigidbody shotInstance;
shotInstance = Instantiate(shotPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
shotInstance.AddForce(barrelEnd.forward * shotSpeed);
sparkBlast();
}
}
// Particle recoil effect
void sparkBlast () {
Rigidbody shotSparks;
shotSparks = Instantiate(sparkPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
Destroy (shotSparks,0.5f);
}
}