Unity当玩家移动时,我如何使我的枪停射?

时间:2019-07-26 18:57:39

标签: c# unity3d

enter image description here我正在制作枪射击脚本,但是我不知道如何在播放器运行时禁用射击。有人可以帮我吗?

void Shoot()
{
    MuzzleFlash.Play();


    RaycastHit hit;
    if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, Range))
    {
        Debug.Log(hit.transform.name);

        EnemyHealth enemy = hit.transform.GetComponent<EnemyHealth>();
        if (enemy != null)
        {
            enemy.TakeDamage(Damage);
        }

    }
}

这是我的角色控制器脚本的移动部分:

void Movement()
{
    transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * WalkSpeed * Time.deltaTime);
    transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * WalkSpeed * Time.deltaTime);

    if (Input.GetKeyDown(KeyCode.LeftShift))
    {
        WalkSpeed = RunSpeed;
    }
    if (Input.GetKeyUp(KeyCode.LeftShift))
    {
        WalkSpeed = DefaultSpeed;
    }
}

2 个答案:

答案 0 :(得分:3)

您可以在其他脚本中设置变量,如下所示:

[Serialize Field]
private GameObject objectWithYourScriptYouNeed; 
private ClassOfScriptYouNeed pS; 


void Start()
{     
    pS = objectWithYourScript.GetComponent<ClassOfScriptYouNeed>();    
    pS.varName = 12345;
}

因此,在您的拍摄脚本中:

Public Bool isMoving;

void Shoot()
{
    //I'm assuming you also dont want muzzleflash to play.
    if (isMoving != true)
    {
        MuzzleFlash.Play();    

        RaycastHit hit;
        if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, Range))
        {

            Debug.Log(hit.transform.name);

            EnemyHealth enemy = hit.transform.GetComponent<EnemyHealth>();
            if (enemy != null)
            {
                enemy.TakeDamage(Damage);
            }
        }
    }
}

您的动作脚本:

//put your shooting scripts name below.
private ShootScript shootScript; 

void start()
{    

    shootScript = GetComponent<ShootScript>();

}

void Movement()
{
    shootScript.isMoving = Input.GetAxis("Vertical") != 0f 
                           || Input.GetAxis("Horizontal") != 0f ; 

    transform.Translate(Vector3.forward * Input.GetAxis("Vertical") 
                        * WalkSpeed * Time.deltaTime);
    transform.Translate(Vector3.right * Input.GetAxis("Horizontal") 
                        * WalkSpeed * Time.deltaTime);

    // GetKey is true on every frame that shift is held down, and false when it isn't
    // GetKeyDown is only true on the first frame in a row that shift is held down    
    if (Input.GetKey(KeyCode.LeftShift))
    {
        WalkSpeed = RunSpeed;
    }
    else 
    {
        WalkSpeed = DefaultSpeed;
    }
}

答案 1 :(得分:2)

设置布尔值isMoving,然后在停止时将其设置为true和false。然后在您的void Shoot中为移动的布尔变量创建一个if语句,并仅在错误时触发。