- Home /
Shoot an object and have it move based on rotation
Here is my situation. I'm trying to make a turret that shoots shells (I already have it set as a child object to a tank). I'm trying to get it to where the shell will be shot in a direction that is based on the rotation of the turret. However, I have tried several things and nothing worked. Here is my code for the bullet
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class Bullet : MonoBehaviour {
public int damage =1;// Use this for initialization
public bool isEnemyShot = false;
public Vector2 speed= new Vector2(10,0);
//public int aimAngle = TankFire.instance.aimAngle;
public Vector2 direction = new Vector2 (1, 0);
private Vector2 movement;
void Start ()
{
DestroyObject (gameObject, 20);//20sec, need to destory to avoid leak
//movement = new Vector2(speed.x, speed.y);
movement = new Vector2(2045, 2045);
rigidbody2D.AddForce (movement);
}
void Update()
{
//rigidbody2D.velocity = transform.forward;
}
void FixedUpdate()
{
//rigidbody2D.velocity = movement;
//apply movement to the rigidbody
}
}
And here is my code for the object shooting it
if(tick >= fireRate)
{
//Instantiate (tankBullet, this.transform.position, Quaternion.Euler (this.transform.rotation.eulerAngles.z, this.transform.rotation.eulerAngles.y,this.transform.rotation.eulerAngles.z));
Instantiate (tankBullet, this.transform.position,this.transform.rotation);
tick = 0;
}
I also need the shell to drop due to gravity using the Unity physics engine.
Thanks to whoever is able to help.
Have you tried making the velocity of the shell be part of transform.forward or transform.right? If you're working in Unity2D make sure you try transform.right, because your forward may be on the Z axis that you are not using.
If you're attaching this script to the bullet itself, have you considered making a variable of type GameObject named GunTip or something of that sort, and then telling the bullet to have the velocity going in the direction of GunTip.forward or GunTip.right
And to make the bullet drop, just attach a rigidbody to the prefab ^~^
Answer by robertbu · Apr 23, 2014 at 03:53 AM
Assuming:
The game object with the Instantiate script is pointing (forward) in the direction you want to fire the Projectile.
You have a Rigidbody component on the projectile prefab
You've constructed the prefab so that the forward of your projectile faces positive 'z' when the rotation is (0,0,0)
The 'tankBullet' variable is of type GameObject.
You could then do:
if(tick >= fireRate)
{
GameObject go = Instantiate (tankBullet, this.transform.position,this.transform.rotation) as GameObject;
go.rigidbody.AddForce(transform.forward * 1000);
tick = 0;
}
The '1000' assumes the projectile has a mass of 1.0 and may need to be adjusted for your app.