简体   繁体   English

Unity2D中的X速度c#

[英]X velocity in Unity2D c#

I'm new to C# and Unity. 我是C#和Unity的新手。 I need to normalize the velocity of my player, but only in the x-direction. 我需要标准化播放器的速度,但只能在x方向上。 My current code is 我当前的代码是

void Update ()
{
if(rb2d.velocity.magnitude > maxSpeed)
    {
        rb2d.velocity = rb2d.velocity.normalized * maxSpeed;
    }

This controls all velocity. 这将控制所有速度。 I tried 我试过了

void Update ()
{
if(rb2d.velocity.x.magnitude > maxSpeed)
    {
        rb2d.velocity.x = rb2d.velocity.x.normalized * maxSpeed;
    }

But I think this was removed in Unity 5. What can I do? 但是我认为这已在Unity 5中删除。该怎么办?

Just divide your velocity X by the velocity's magnitude, which is essentially what normalize does. 只需将速度X除以速度的大小,这基本上就是归一化的作用。

// Make a copy of the current velocity.
Vector2 velocity = rb2d.velocity;

// Divide the x component by magnitude, equivalent to normalizing it.
velocity.x = velocity.x / velocity.magnitude;

// velocity now only has its x component normalized and y untouched
rb2d.velocity = velocity * maxSpeed;

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

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