- Home /
Bullet Movement 2D
I'm struggling to make my bullet prefab move forward at a constant velocity when spawned. This is for a top down 2D shooter. Using AddForce doesn't have the desired effect. Here is my code:
PlayerShooting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
public Transform firePoint;
public GameObject shellPrefab;
public float shotDelay = 2f; //Delay bewteen shots
private float timestamp;
void Update()
{
if (Time.time >= timestamp && (Input.GetButtonDown("Fire1")))
{
Shoot();
timestamp = Time.time + shotDelay; //Shot delay is used here
}
}
void Shoot()
{
GameObject shell = Instantiate(shellPrefab, firePoint.position, firePoint.rotation);
Debug.Log("Shooting");
}
}
PlayerBullet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBullet : MonoBehaviour
{
public float bulletSpeed;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
rb.velocity = new Vector2(bulletSpeed, bulletSpeed);
}
}
When spawned, the bullet doesn't move at all. I've been struggling with this problem for weeks. I'm self taught, so please bear with me.
Answer by Koyemsi · Jun 06 at 12:49 AM
Maybe the problem is simply that you haven't defined the value of bulletSpeed ? It's zero by default, so you're giving the rigid body a null velocity.
I feel like an idiot but thank you so much. All I had to do was enable the script, bulletSpeed already have a value of two. Have a good day!
Turns out there is a major problem. When I shoot, no matter the direction, the bullet moves towards the top right of the screen.
Fixed the problem with this placed in the Update function:
transform.Translate(Vector2.up * bulletSpeed * Time.deltaTime);
Your answer
Follow this Question
Related Questions
2D Shooting Prefab 1 Answer
Shooting around defense position without contact 1 Answer
Shooting at an object 2 Answers
Instantiate after setting values? 0 Answers