Hello,
I have a 3d character seen as 2d using a Orthographic camera and when I try to fire the weapon using a mouse click, the character upper body rotates based on the point of my click, the problem is that the upper body moves weirdly using this code :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
public class PlayerController : MonoBehaviour {
public float bulletSpeed;
public Transform ShotSpawm;
public Transform Player;
public GameObject bullet;
private RaycastHit hit;
private float nextFire;
void Awake ()
{
}
void Update ()
{
//block firing over ui elements
if (EventSystem.current.IsPointerOverGameObject ())
return;
else {
if (Input.GetButton ("Fire1") && Time.time > nextFire && Time.timeScale != 0) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
if (hit.transform.name == "ShootBoundary") {
Debug.Log ("Invalid click");
} else {
//rotate player's body based on mouse click position
Vector3 pos = Camera.main.WorldToScreenPoint (Player.position);
Vector3 dir = Input.mousePosition - pos;
float anglee = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
//anglee -= 90;
Player.rotation = Quaternion.AngleAxis (anglee, Vector3.forward);
nextFire = Time.time + fireRate;
Fire ();
}
}
}
}
}
private void Fire()
{
GameObject currentBullet = (GameObject)Instantiate(bullet, ShotSpawm.position, ShotSpawm.rotation);
Vector3 angle = Player.eulerAngles;
currentBullet.transform.eulerAngles = angle;
Vector3 forceVector = currentBullet.transform.right;
currentBullet.GetComponent<Rigidbody>().AddForce(forceVector * bulletSpeed * 1.5f, ForceMode.Impulse);
}
}
The character rotates only on a top based position as shown in the below image, though the bullets that are fired move in a correct trajectory :
So I noticed that if I decrease the anglee variable by 90, the body will face the mouse click position, but obviously the bullets will be shot in the ground, as shown below:
Last thing I tried was not only to decrease the anglee variable by 90 but also remove the added eulerAngles to the instantiated bullet, which made the bullets go in the right trajectory but they would rotate weirdly and after a while disappear out of the camera view because the z transform value increased too much.
If anyone has a solution for this issue, to make the bullets follow the player’s upper body’s position and rotation, I would greatly appreciate it.
If I need to add any more info regarding the script/game scene let me know.
Thanks,
Alexander