首页 > 解决方案 > 在 Unity 中发射弹丸

问题描述

我正在尝试使用 Unity 在游戏中构建武器。我的子弹产生了,但我似乎无法在实例化时施加力以使它们真正开火。

我的武器脚本

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

public class Weapon : MonoBehaviour {

    public Rigidbody2D projectile;
    public float forceMultiplier;
    public Vector2 direction;

    public Transform firePoint;

    private float timeBtwShots;
    public float startTimeBtwShots;

    public void Fire(float force, Vector2 direction)
    {
        Instantiate(projectile, firePoint.position, transform.rotation);  
        projectile.AddForce(direction * force);
    }

    // Update is called once per frame
    void Update () {
        if (timeBtwShots <= 0)
        {
            if (Input.GetKeyDown(KeyCode.Return))
            {
                Fire(forceMultiplier, direction);
                timeBtwShots = startTimeBtwShots;
            }
        }
        else 
        {
            timeBtwShots -= Time.deltaTime;
        }
    }
}

标签: c#unity3d

解决方案


您需要将力添加到生成的对象而不是预制件。你的代码应该是这样的:

    public void Fire(float force, Vector2 direction)
    {
        Rigidbody2D proj = Instantiate(projectile, firePoint.position, transform.rotation);  
        proj.AddForce(direction * force);
    }


推荐阅读