【问题标题】:How can I change a bullet shooting speed and keep the bullet shooting distance using physics?如何使用物理改变子弹射击速度并保持子弹射击距离?
【发布时间】:2020-06-07 23:34:46
【问题描述】:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using UnityEditor;
using UnityEngine;

public class ShootBullets : MonoBehaviour
{
    public float bulletDistance;
    public bool automaticFire = false;
    public float fireRate;
    public Rigidbody bullet;

    private float gunheat;
    private bool shoot = false;
    private GameObject bulletsParent;
    private GameObject[] startpos;

    // Start is called before the first frame update
    void Start()
    {
        bulletsParent = GameObject.Find("Bullets");
        startpos = GameObject.FindGameObjectsWithTag("Pod_Weapon");
    }

    void Fire()
    {
        for (int i = 0; i < startpos.Length; i++)
        {
            Rigidbody bulletClone = (Rigidbody)Instantiate(bullet, startpos[i].transform.position, startpos[i].transform.rotation, bulletsParent.transform);

            bulletClone.velocity = transform.forward * bulletDistance;
            // The bullet or any ammo/weapon should be on Y rotation = 0
            Destroy(bulletClone.gameObject, 0.5f);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (automaticFire == false)
        {
            if (Input.GetMouseButtonDown(0))
            {
                Fire();
            }
        }
        else
        {
            if (shoot == true)
            {
                    Fire();

                    shoot = false;
            }
        }

        if (gunheat > 0) gunheat -= Time.deltaTime;

        if (gunheat <= 0)
        {
            shoot = true;
            gunheat = fireRate;
        }
    }
}

我想像这条线一样保持距离:

bulletClone.velocity = transform.forward * bulletDistance;

还能控制子弹速度。也许这是使用物理时的问题? 我的问题是子弹射得太快了。

问题是是否可以使用物理控制速度并保持距离? 应该从 Update 或 FixedUpdate 调用函数 Fire 吗?

【问题讨论】:

  • 我会尝试写一个更具描述性的标题。我认为问题出在数学或计算上。
  • 请更具体。可能性是无穷无尽的。您是想控制整个生命周期的速度,还是想将子弹速度限制在最大值。您也可以将速度除以一个值。
  • @flyingchris 终生。我想保持距离,例如 50 并且我希望能够控制距离上的速度。所以距离是50,速度可以是10或20或30。
  • distance = velocity * time 所以velocity = distance / time 你可以在设置之前计算速度。例如 v = 50 / 10s , v = 5
  • 你的子弹有重力吗?或者只是向前移动。

标签: c# unity3d


【解决方案1】:

我的意思是“终生”不同,但没关系。速度目前只设置一次,所以它只取决于你发射子弹的距离。不是离目标的距离。

如果你想在方程中保持距离但减小结果,你有没有想过除以速度? IE添加这样的东西

bulletClone.velocity = transform.forward * bulletDistance / 3;

您还可以将速度与最大值进行比较,然后决定选择哪个 IE

if(bulletDistance < 30)
{
bulletClone.velocity = transform.forward * bulletDistance;
}
else
{
bulletClone.velocity = transform.forward * 30
}

您可以将速度设置为您想要的任何值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多