Hello, I am new to unity and I’m trying to make a 2D shooter game. I have made a function that instantiates a bullet when space is pressed, but I want to make the bullets decelerate after being shot. I’m not sure how to do this since I’m not sure if you’re able to modify the bulletClone.velocity since it’s a local variable
Here’s my code, any help would be very much appreciated!
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.UIElements;
using static UnityEditor.PlayerSettings;
public class PlayerMovement : MonoBehaviour
{
// game objects / components
public GameObject Player;
public Rigidbody2D playerRB;
public Rigidbody2D bulletRB;
public GameObject bullet;
// variables
public float movespeed = 1.5f;
public float firespeed = 5f;
public float inputX = 0f;
public float inputY = 0f;
public float bulletDecelerate = 1f;
public bool bulletIsAlive = false;
public float reloadSpeed = 1;
public float shotCooldown = 0;
public Rigidbody2D shoot()
{
Debug.Log("shot");
// instantiate the bullet at the player's position
Rigidbody2D bulletClone;
bulletClone = Instantiate(bulletRB, playerRB.position, Quaternion.identity);
// shoot bullet in same direction as player
Vector2 bulletCloneVelocity = new Vector2(inputX, inputY);
bulletClone.velocity = bulletCloneVelocity;
bulletIsAlive = true;
//return bulletClone;
return bulletClone;
}
public void dash()
{
// add a dash function. at the start of the game, the player has no gun and must dash into enemies to kill them. dash cooldown. if not dashing you will take damage.
}
void Start()
{
playerRB = Player.GetComponent<Rigidbody2D>();
bulletRB = bullet.GetComponent<Rigidbody2D>();
}
void Update()
{
// player movement
inputX = Input.GetAxis("Horizontal");
inputY = Input.GetAxis("Vertical");
Vector2 moveVector = new Vector2(inputX, inputY);
playerRB.position += moveVector * (movespeed * Time.deltaTime);
// if button is pressed, shoot
if (Input.GetKey(KeyCode.Space) && (shotCooldown >= reloadSpeed))
{
shoot();
shotCooldown = 0;
}
// if any bullets have been shot, reduce their speed and destroy if speed = 0
if (bulletIsAlive)
{
// reduce speed
bulletClone.velocity -= bulletDecelerate;
}
shotCooldown += 1 * Time.deltaTime;
}
}