繁体   English   中英

C#Unity-当我在游戏中单击空格键时,如何启用“ PlayerMovement”脚本和“使用重力”复选框(刚体)?

[英]C# Unity - How do I make my “PlayerMovement” script and “Use Gravity” checkbox (rigidbody) enable when I click SPACEBAR in game?

我一周前开始制作第一款游戏,但在编码方面遇到了一些问题。 基本上,我制作了一款您可以玩球的游戏。 目标是躲避障碍并达到关卡的尽头。

我制作了一个重生器,每当您死亡时,它都会将球放在地图的开始处。 我的问题是,一旦球重新产生,球就会再次开始运动。

到目前为止,我为防止Ball在开始时移动而所做的事情是,我已禁用Ball的PlayerMov脚本(玩家移动)以及Rigidbody组件中的“使用重力”复选框。 所以现在我的球卡在了无法移动的起始位置。

那我需要什么帮助呢? 我希望人类玩家按下空格键以使球的PlayerMov脚本和“使用重力”复选框(在Rigidbody中)启用。 因此,它不再是在重生之后立即移动球,而是将等待人类玩家在开始之前按下空格键。

您在下面看到的脚本是我的EnableMovement脚本,在该脚本中我试图解决此问题。 但是出了点问题,我不太确定这是什么。

代码错误

您必须将其放置在update()方法中,因此,如果按下空格键,脚本将检查每帧。

void Update()
{
    if (Input.GetKey(KeyCode.Space)) //notice the removing of the ;
    {
        GetComponent<PlayerMov>().enabled = true;
    }
}

输入此代码时,您的代码有误:

if (Input.GetKey(KeyCode.Space)); //notice the ;
{
    GetComponent<PlayerMov>().enabled = true;
}

这与以下内容相同:

if (Input.GetKey(KeyCode.Space))
    ; //Do nothing
//there is a scope that will be executed
{
    GetComponent<PlayerMov>().enabled = true;
}

和这完全一样:

if (Input.GetKey(KeyCode.Space))
{
    ; //Do nothing
}
//there is a scope that will be executed
{
    GetComponent<PlayerMov>().enabled = true;
}

编辑:我的错误,您要更改的属性未enabled Rigidbody 这是IsKinematic 另外,您可能也想禁用碰撞。 我在下面编辑了我的代码。

一种简单的解决方案是在运行游戏时禁用物理功能,并在玩家按下空格时启用物理功能。 Rigidbody.IsKinematic属性设置为true意味着GameObject将不受物理影响。 这样,您无需触摸重力设置或禁用脚本。

Rigidbody _rigidbody;    

void Start() // or could go in the Awake() method depending on your game
{
    _rigidbody = GetComponent<Rigidbody>();
    TogglePhysics(false);
}

void Update()
{
    if (Input.GetKey(KeyCode.Space))
    {
        TogglePhysics(true);
    }
}

void TogglePhysics(bool isEnabled)
{
    // IsKinematic needs to be true to disable physics. See the documentation for IsKinematic.
    _rigidbody.IsKinematic = !isEnabled; 
    _rigidBody.detectCollisions = isEnabled;
}

// When respawning, call TogglePhysics(false);

暂无
暂无

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

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