- Home /
Won't Shoot if Y Rotation Value Is Negative
My program allows a player (which the main camera) to shoot balls in the direction the camera is angled/facing. This works except when the y rotation value of the camera is a negative number.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
public float speed;
public GameObject projectile;
public GameObject hit_object;
private Vector3 moveDirection = Vector3.zero;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 pos = transform.position;
pos.y = 3;
transform.position = pos;
if (Input.GetKey(KeyCode.RightArrow))
{
transform.localPosition += transform.right * Time.deltaTime * speed;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position += -transform.right * Time.deltaTime * speed;
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.position += -transform.forward * Time.deltaTime * speed;
}
if (Input.GetKey(KeyCode.UpArrow))
{
transform.position += transform.forward * Time.deltaTime * speed;
}
if (Input.GetKeyDown(KeyCode.F))
{
GameObject bullet = Instantiate(projectile, transform.position, transform.rotation);
bullet.GetComponent<Rigidbody>().AddRelativeForce(new Vector3(0, 0, 4000));
}
if (Input.GetKeyDown(KeyCode.E))
{
var pos_x = transform.position.x + Random.Range(-500F, 500F);
var pos_z = transform.position.z + Random.Range(-500F, 500F);
Instantiate(hit_object, new Vector3(pos_x, transform.position.y, pos_z), transform.rotation);
}
transform.Rotate(0f, Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0f, Space.World);
transform.Rotate(-Input.GetAxis("Vertical") * speed * Time.deltaTime, 0f, 0f, Space.Self);
}
}
This happens regardless of the size of the sphere (has Rigidbody component) or the current position of the camera.
As you can see, the balls that were fired went towards the top of the field based on the snippet view which is a direct result of the balls fired at a y-rotation value from 0 to 180 and rolling away due to physics. There are no balls at the bottom of the screen since if the rotational y value is negative, the balls will be shot at 0 or 180 degrees, whichever is closer.
How do I allow balls to be fired even if the rotational value of y is negative? The y-value mentioned:
Answer by aldonaletto · Jul 13, 2017 at 01:01 AM
There's nothing wrong with your script - I've tested it and the projectiles were shot in the camera's forward direction independently of its rotation, as expected. I suspect that you may have something behind the camera, some forgotten object or collider that is blocking the projectiles when the camera turns to its direction.
You were right...ish. The unnecessary CharacterController component disallowed me to shoot when y was negative. Thank you so much!
Answer by Jwizard93 · Jul 12, 2017 at 11:34 PM
bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 4000);
Try swapping out line 44 with this