繁体   English   中英

通过C#Unity投掷游戏对象

[英]Throw a game object via C# Unity

遇到引发游戏对象的麻烦。 我有一个2D游戏,我要扔的游戏对象是手榴弹。 目前,我有以下代码:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]

public class SoldierController : MonoBehaviour
{

    public GameObject grenadeObject;

     void Start()
        {
            grenadeObject.SetActive(false); 
        }

    void Update()
    {
     if (Input.GetKeyDown(KeyCode.I))
                    {
                        grenadeObject.SetActive(true);
                        animator.SetBool("Grenade", true);
                        GrenadeThrow();
                        //speed = Mathf.Lerp(10, 0, Time.deltaTime);
                       // grenadeObject.transform.Translate(Vector3.forward * 10);
                        StartCoroutine(GrenadeCooldown());
                    }

     }

    void GrenadeThrow()
        {
            StartCoroutine(COPlayOneShot("Grenade"));
            Instantiate(grenadeObject, new Vector3(10 * 2.0F, 0, 0), Quaternion.identity);
        }


        IEnumerator GrenadeCooldown()
        {
            canFire = false;
            yield return new WaitForSeconds(0.01f);
            //rifleMuzzle.GetComponent<ParticleSystem>().top();
            canFire = true;
            animator.SetBool("Grenade",false);
        }
}

我希望该对象至少可以从角色手中抛出,除非什么也没有发生。 任何帮助/?

您需要在grenadeObject预制件上具有一个组件,例如Grenade脚本。 在其中,您将拥有一个Vector3来确定其应走的方向,并具有一个浮点数来确定速度。 在该脚本的Start() ,您将使用速度和方向来发射手榴弹。 速度和方向由您在问题中提供的班级分配。

这是一个手榴弹类的例子:

public class Grenade : Monobehaviour {

    public Vector3 direction;
    public float speed;

    void Start () {

        // initiate movement of the grenade

    }

}

您的班级从以下问题进行了更新:

public GameObject grenadeObject;

void Update() {

   if (Input.GetKeyDown(KeyCode.I)) {

       animator.SetBool("Grenade", true);
       GrenadeThrow();

    }

}

void GrenadeThrow() {

    StartCoroutine(COPlayOneShot("Grenade")); // unknown function
    Grenade grenade = Instantiate(grenadeObject, new Vector3(10 * 2.0F, 0, 0), Quaternion.identity).GetComponent<Grenade> ();
    grenade.direction = Vector3.one; // change this to the appropriate direction
    grenade.speed = 10f; // change this to the appropriate speed

}


IEnumerator GrenadeCooldown() {

    canFire = false;
    yield return new WaitForSeconds(0.01f);
    //rifleMuzzle.GetComponent<ParticleSystem>().top();
    canFire = true;
    animator.SetBool("Grenade",false);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM