统一的射弹产生但没有加快速度?

时间:2019-02-15 18:36:32

标签: c# unity3d

这是我的代码吗,有人知道吗,或者谁能发现为什么我的弹丸生成后为何保持静止?弹丸是预制壳,谢谢您的事先帮助。

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");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

通常也不建议设置刚体的速度,但是可以使用Rigidbody.AddForce()方法向刚体施加力。如果只想在开始时添加力,则可以在函数中将力模式设置为脉冲,例如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");
        }
    }
}

希望这会有所帮助!