Detail:Making a 2d cannon shooter which shoots in the sky for flying planes.I have a cylinder as a cannon,A sphere as a prefab(bullet).Attached at the tip of the cannon is a locator from which the bullet instannce comes out.I need to rotate the cannon.This is my script.Just started C#(3-4 days):
cannon:using UnityEngine;
using System.Collections;
public class player : MonoBehaviour {
public GameObject bullet;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("space"))
{
Instantiate(bullet,GameObject.Find("bullet_spawn").transform.position,Quaternion.identity);
bullet.rigidbody.AddForce(Vector3.forward * 200000);
}
if (Input.GetKey("left"))
{
this.transform.Rotate(Vector3.forward);
}
}
}
The problems are:
1.When ever I press "space"(fire) there is always a first sphere that is created which just sits and the subsequent ones move forward.If I pause and fire again this thing happens again.
2.When i start rotating the cylinder(cannon) the spheres just pop out and dont shoot out and when i stop rotating the shooting starts again but with the first one coming out with like no power.
if you already have your cannon ball you dont need to instantiate an other one, you can use the existing one
if you want to rotate the cannon to make an angle you code wont work cus it will just have force on X axiz meanin in the <- or -> ways
you can try this
float cannonAngle=0;
cannonAngle = cannon.transform.rotation.eulerAngles.z; // this gives you the inclination if you have your 2d game in just X and Y axis
Vector3 bulletForce = new Vector3(20000*mathf.cos(cannonAngle*180/mathf.PI),20000*mathf.sin(cannonAngle*180/mathf.PI),0);
bullet.rigidbody.AddForce(bulletForce);
//or you can use
bullet.rigidbody.velocity = bulletForce;
any of AddForce or velocity works for movin the object, the difference is that with one the cannon ball will fly at amazin speed, just play a little with the values of your foce when you decide wich one will you use