简体   繁体   English

Unity 2D以特定角度启动gameObject而不影响速度

[英]Unity 2D launch gameObject at a specific angle without affecting speed

I am working on a game where i need to shoot the ball at an angle and power defined by 2 sliders (1 angle slider, 1 power slider). 我正在做一个游戏,我需要以2个滑杆(1个滑杆,1个滑杆)定义的角度和力量射击球。 I currently have this code to control the launching of the ball: 我目前有以下代码来控制球的发射:

  public void shoot()
{
    float angle = angleSlider.GetComponent<Slider>().value;
    float power = powerSlider.GetComponent<Slider>().value;

    gameObject.SetActive(false);

    ball.GetComponent<Rigidbody2D>().simulated = true;

    Vector2 releaseVector = Quaternion.AngleAxis(angle, transform.up) * transform.forward;
    ball.GetComponent<Rigidbody2D>().velocity = releaseVector * (power/3);


}

with this current code it works almost perfect apart from one thing. 用当前的代码,除了一件事情,它几乎可以完美地工作。 When the angle is like between 30 and 60, the ball is launched well but if i set it to 0 degrees the ball would barely move and on the contrary if i set it to 90 degrees, the ball launches with much more power. 当角度介于30到60之间时,球会很好地发射,但是如果我将其设置为0度,则球几乎不会移动,相反,如果我将其设置为90度,则球会以更大的力量发射。 How can i set a constant speed for all degrees so that the speed is only affected by the power slider only please? 我如何才能为所有度数设置一个恒定速度,以便该速度仅受电动滑块的影响? Thanks. 谢谢。

Typically, you shouldn't set the velocity of a rigidbody directly. 通常,您不应该直接设置刚体的velocity Per the Unity docs ... 根据Unity文档 ...

In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour. 在大多数情况下,您不应该直接修改速度,因为这会导致不切实际的行为。

Instead, you usually want to impart a physical impulse to the ball using an API like AddForce or AddRelativeForce 相反,您通常希望使用诸如AddForceAddRelativeForce之类的API向球施加物理冲动

That is easy.. You have to normalize the releaseVector. 这很容易..您必须标准化releaseVector。

  ball.GetComponent<Rigidbody2D>().velocity = releaseVector.normalized * (power/3);

Then adjust the power to what you want. 然后根据需要调整电源。 That way you will have the direction u wanted and speed depends on the power value. 这样,您将获得所需的方向,速度取决于功率值。

If you want to know what normalize do, you can find more information here; 如果您想知道规范化的作用,可以在这里找到更多信息。 https://docs.unity3d.com/ScriptReference/Vector3.Normalize.html https://docs.unity3d.com/ScriptReference/Vector3.Normalize.html

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

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