- Home /
How to: shoot bullets from an rotating object
Hello guys!! noob here. I am trying to develop a 2d game in unity. I have a player in middle of the screen and a gun that is orbiting around him. How can I make the gun fire bullets in the direction of rotation? Right now i managed to make the bullets appear when click, but they dont come out of the gun. They come out from the same position everytime this is the bullet script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class BulletScript : MonoBehaviour
{
Rigidbody2D rb2d;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
rb2d.velocity = new Vector3(0,3,0);
//transform.Translate(0, Time.deltaTime * 10, 0);
}
}
and this is the spawn bullet script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootObject : MonoBehaviour
{
public float m_speed;
Object bulletRef;
// Start is called before the first frame update
void Start()
{
bulletRef = Resources.Load("Bullet");
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
GameObject bullet = (GameObject)Instantiate(bulletRef);
bullet.transform.localPosition = new Vector3(0,0,0);
//bullet.transform.Translate(0, Time.deltaTime * 10, 0);
}
}
}
Answer by lgarczyn · Dec 21, 2019 at 10:58 PM
Your bullet script is a bit useless here, since you only need to set the velocity once if the drag is 0.
GameObject bullet = (GameObject)Instantiate(bulletRef);
bullet.transform.localPosition = new Vector3(0,0,0);
bullet.GetComponent<RigidBody2D>().velocity = transform.right * bulletSpeed
//or
bullet.GetComponent<RigidBody2D>().velocity = transform.up * bulletSpeed
Chose which line depending on what is the forward axis of the gun.
If you need a bullet script that knows its velocity, do something like:
bullet.GetComponent<Bullet>().SetVelocity(transform.up * bulletSpeed);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Instantiate random platforms 0 Answers
My character needs to teleport back before he can float, how do I fix that? 1 Answer