简体   繁体   English

用单个操纵杆旋转3D对象

[英]Rotating 3D object with a single joystick

I am creating a game in Unity 3d that is using a single joystick. 我正在Unity 3d中创建一个使用单个操纵杆的游戏。 I am trying to figure out how I can rotate a 3d object using the joystick correctly. 我试图弄清楚如何正确使用操纵杆旋转3d对象。 Basically when the joystick is pushed up (or forward) the object will rotate forward and vice versa for when it is pushed down. 基本上,当操纵杆被向上(或向前)推时,对象将向前旋转,反之亦然。 My problem is getting the object to rotate correctly if I were to push the up diagonally to the left or right. 我的问题是,如果将对角线向左或向右推,则使对象正确旋转。

My joystick uses gives values (0, 1) for up, (0, -1) for down, (1, 0) for right, and (-1, 0) for left. 我的操纵杆使用的值为(0,1)表示向上,(0,-1)表示向下,(1,0)表示右侧,(-1,0)表示左侧。

How do I get the object to rotate forward or backward and toward the diagonal direction on a joystick? 如何使对象在操纵杆上向前或向后以及向对角线方向旋转? (I'm sorry if this is confusing. I am trying to ask this as simple as I can). (很抱歉,这令人困惑。我正在尝试尽可能简单地问这个问题)。

Right now this is what I am using to rotate: 现在,这就是我要旋转的内容:

if ((x > 0 && x < .2f) || (x < 0 && x > .2f)) x = 0;
if ((y > 0 && y < .2f) || (y < 0 && y > .2f)) y = 0;

if (x < 0) car.transform.Rotate(car.transform.forward.x * 10f, car.transform.forward.y * 10f, -car.transform.forward.y * 10f);
else if (x > 0) car.transform.Rotate(car.transform.forward.x * 10f, car.transform.forward.y * 10f, car.transform.forward.y * 10f);
else car.transform.Rotate(car.transform.forward.x * 10f, car.transform.forward.y * 10f, 0f);

It looks like you don't understand Transform.Rotate (second overload). 看来您不了解Transform.Rotate (第二次重载)。

This is the signature of the method: 这是方法的签名:

public void Rotate(float xAngle, float yAngle, float zAngle, Space relativeTo = Space.Self);

xAngle is the number of degrees to rotate around the x axis. xAngle是围绕x轴旋转的度数。 Passing a component of the forward vector ( car.transform.forward.x ) is trying to put a unit vector component into a parameter accepting an angle. 传递正向矢量的一个分量( car.transform.forward.x )试图将单位矢量分量放入接受角度的参数中。 The concepts and units simply don't match, so the result will be impossible to describe. 概念和单位根本不匹配,因此结果无法描述。

Instead, you should rotate using angles based on the joystick position. 相反,您应该根据操纵杆位置使用角度旋转。 Relative mode (the default Space.Self ) will mean that the joystick acts relative to the object's current rotation. 相对模式(默认为Space.Self )表示操纵杆相对于对象的当前旋转起作用。

Something like this should do it, where x and y are your joystick positions: 应该这样做,其中xy是您的操纵杆位置:

car.transform.Rotate(y, x, 0)

You can either carefully look at which joystick axes match with which Unity axes, or try moving the x and y around until it works right. 您可以仔细查看哪些操纵杆轴与哪些Unity轴匹配,或者尝试四处移动xy直到正确工作。 You might also need to negate x or y depending on your preference. 您可能还需要根据自己的喜好取反xy

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

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