简体   繁体   English

Unity 2D 手游:如何让世界重力跟随设备倾斜

[英]Unity 2D mobile Game: How to make the world gravity follow device tilt

I know it could be a basic question for Unity developers.我知道这对 Unity 开发人员来说可能是一个基本问题。 But I am struggling to find answers for this problem.但我正在努力寻找这个问题的答案。 I want to move all objects in my game screen based on device acceleration.我想根据设备加速移动游戏屏幕中的所有对象。 I only think of 2 possibles solutions:我只想到两种可能的解决方案:

1st: change the whole world gravity based on device tilt第一:根据设备倾斜改变整个世界的重力

2nd: apply the forces to all objects or change the velocity of all objects (I tried changing the velocity but the game got lagging)第二:对所有物体施加力或改变所有物体的速度(我尝试改变速度但游戏滞后)

Is there any good way to make 2D game objects smoothly move based on device tilt?有没有什么好方法可以让 2D 游戏对象根据设备倾斜度平滑移动?

You can do this by modifying Physics2D.gravity .您可以通过修改Physics2D.gravity来做到这Physics2D.gravity It will change the gravity of all GameObjects in the scene.它将改变场景中所有游戏对象的重力。

Physics2D.gravity = Input.acceleration * 50; would have worked but because Input.acceleration has low, mid and high values, it wont work.本来可以工作,但因为Input.acceleration具有低、中和高值,所以它不起作用。 So you can't assign Input.acceleration directly to Physics2D.gravity .所以,你不能分配Input.acceleration直接Physics2D.gravity

You need to turn on you device then use Debug.Log(Input.acceleration) to view the low, middle and high values of each axis then you can use if statement and temporary Vector2 value to get what 2D value to assign to Physics2D.gravity .您需要打开设备,然后使用Debug.Log(Input.acceleration)查看每个轴的低、中和高值,然后您可以使用if语句和临时Vector2值来获取要分配给Physics2D.gravity二维值.

Also for any GameObject you want the accelerometer to affect more , less or not at-all , you can modify the RigidBody Gravityscale of that GameObject.此外,对于您希望加速度计影响更多更少根本不影响的任何游戏对象,您可以修改该RigidBody GravityscaleRigidBody Gravityscale

The gravity applied to all rigid bodies in the scene can be changed by setting Physics2D.gravity .可以通过设置Physics2D.gravity更改应用于场景中所有刚体的重力。

Note: Make sure you also set rigidbody.useGravity = true (for gravity to affect the objects).注意:确保你也设置了rigidbody.useGravity = true (重力影响物体)。

Example: Physics2D.gravity = new Vector2(x, y);示例: Physics2D.gravity = new Vector2(x, y);

Physics.gravity Unity APIPhysics.gravity Unity API

Input-acceleration Unity API 输入加速 Unity API

Place this in the update() block of any element.将它放在任何元素的 update() 块中。

Physics2D.gravity is a "global" value that takes a Vector2 for value. Physics2D.gravity 是一个以 Vector2 为值的“全局”值。

Debug.Log(Input.acceleration);
Physics2D.gravity = new Vector2(Input.acceleration.x*1.5f, Input.acceleration.y*1.5f);

(You may edit/remove the multiplying floats in each input acceleration property, I added them just for some exponential gravity speed.) Note: This will impact all the rigidbodies. (您可以编辑/删除每个输入加速度属性中的乘法浮点数,我添加它们只是为了一些指数重力速度。) 注意:这将影响所有刚体。

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

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