【发布时间】:2020-02-16 21:06:48
【问题描述】:
我正在学习 Unity 中的 Udemy 2D 教程来创建 2D 像素游戏。语言是 C#。 在我的播放器脚本中,我有一个攻击功能,例如当我按下回车键时,一把剑从玩家的身体中飞出,沿着玩家正在看的方向(就像在旧的塞尔达游戏中一样)。为了让玩家在攻击时冻结一点,同时也限制剑的范围,我使用了第二个脚本,叫做剑,问题是我认为脚本根本没有被调用(我试过即使在 void start 中也可以进行一些调试,但什么也没有。
代码如下:
-这是我的攻击代码:
void attack()
{
canMove = false;
GameObject newSword = Instantiate(sword, transform.position, sword.transform.rotation);
#region //SwordRotation
int swordDir = anim.GetInteger("dir");
if (swordDir == 0)
{
newSword.transform.Rotate(0, 0, 0);
newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.up * thrustPower);
}
else if (swordDir == 1)
{
newSword.transform.Rotate(0, 0, 180);
newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.down * thrustPower);
}
else if (swordDir == 2)
{
newSword.transform.Rotate(0, 0, 90);
newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.left * thrustPower);
}
else if (swordDir == 3)
{
newSword.transform.Rotate(0, 0, -90);
newSword.GetComponent<Rigidbody2D>().AddForce(Vector2.right * thrustPower);
}
#endregion
}
这是我的 Sword 代码:我使用它主要是因为在进行攻击时 canMove 设置为 false,所以我必须在短时间内将其重置为 true 才能再次移动。
PS:我注意到剑脚本是直接在unity界面的scripts文件夹中创建的,乍一看并没有与任何游戏对象关联。
{
public float timer;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().canMove = true;
Destroy(gameObject);
}
}
}
【问题讨论】:
-
PS2:我很自然地将Player标签设置为“Player”。
-
那么您是否真的将脚本附加到游戏对象上?
-
在教程中他没有这样做,当我尝试这样做并将脚本附加到剑精灵时,当我第一次攻击它时,玩家攻击,剑出现了,并且然后被破坏了,但是当我再次攻击时没有任何反应,剑不会再次出现
-
@DjamelMesbah 一般来说,不销毁和重生而是只启用和禁用剑会更有效,所以它可能不是最好的教程......在哪些脚本中方法以及这些脚本附加到什么?
-
攻击方式在player Script中(有移动和血量显示,第二种(我们摧毁剑的地方)在Sword中,更准确地说,他对单击Scripts文件夹并直接添加ac#脚本并将其命名为Sword并放置该代码,而不将其附加到任何游戏对象。是的,你说的看起来更有效率和逻辑,我会尝试实现它,谢谢man