lukeet
lukeet

Reputation: 511

unity projectile spawns but doesn't pick up velocity?

This is my code does anyone know or can anyone spot why my projectile remains stationary once it's spawned in? the projectile is the prefab shell thanks for your help in advance.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TankBehaviour : MonoBehaviour
{

    public GameObject shellPrefab;
    public Transform fireTransform;
    private bool isFired = false;


    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

        transform.position += transform.forward * y;
        transform.Rotate(0, x, 0);

        if (Input.GetKeyUp(KeyCode.Space) && !isFired)
        {
            Debug.Log("fire!");
            Fire();
        }
    }

    void Fire()
    {
        //isFired = true;
        GameObject shellInstance = Instantiate(shellPrefab,
                                                fireTransform.position,
                                                fireTransform.rotation) as GameObject;

        if (shellInstance)
        {
            shellInstance.tag = "Shell";
            Rigidbody shellRB = shellInstance.GetComponent<Rigidbody>();
            shellRB.velocity = 15.0f * fireTransform.forward;
            Debug.Log("velocity");
        }
    }
}

Upvotes: 1

Views: 169

Answers (1)

Eric Bishop
Eric Bishop

Reputation: 529

It is also generally discouraged to set the velocity of a rigidbody, but you can use the Rigidbody.AddForce() method to add force to a rigidbody. When you just want add force at the start, you can set the force mode in the function to impulse, like this rb.AddForce(Vector3.forward, ForceMode2D.Impulse);

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TankBehaviour : MonoBehaviour
{

    public GameObject shellPrefab;
    public Transform fireTransform;
    private bool isFired = false;

    public float bulletSpeed;

    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

        transform.position += transform.forward * y;
        transform.Rotate(0, x, 0);

        if (Input.GetKeyUp(KeyCode.Space) && !isFired)
        {
            Debug.Log("fire!");
            Fire();
        }
    }

    void Fire()
    {
        //isFired = true;
        GameObject shellInstance = Instantiate(shellPrefab, fireTransform.position, fireTransform.rotation) as GameObject;

        if (shellInstance)
        {
            shellInstance.tag = "Shell";
            Rigidbody shellRB = shellInstance.GetComponent<Rigidbody>();
            shellRB.AddForce(15f * transform.forward, ForceMode.Impulse);
            Debug.Log("velocity");
        }
    }
}

Hope this helps!

Upvotes: 2

Related Questions