So I’m trying to make a mobile game where you can tilt your phone to make a cube go left/right. If I tilt my phone the cube tumbles and move either left or right which is how I want it. However if the phone’s tilted too much the cube gets an incredible speed which I really do not want.
I have been looking for a solution everywhere and tried a lot of things to fix my issue but it never turns out well. I tried setting a max velocity on the cube but that breaks other mechanics of my game. I’ve also tried detecting if the phone is in portrait mode, if so the cube got a force the opposite way to cancel the extreme speed but that didn’t really solve it either and just turned out wonky.
What I want to achive is:
If the phone gets tilted with an angle of 25° or more the velocity won’t increase anymore.
Like so:
(Cube wont move)
(Cube moves at max speed in the right direction.)
Is it even possible to achieve want I want? If yes, how? If no, what should I do instead?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
float speed = 25F;
public Rigidbody Cube;
public float currentHeight;
public float previousHeight;
public float travel;
void Start()
{
Cube = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
{
Vector3 accel = Input.acceleration;
Cube.AddForce(accel.normalized.x * speed, 0, 0);
}
//Below is irrelevant for my issue with tilt limit!
//Increasing gravity when the cube is falling.
currentHeight = transform.position.y;
travel = currentHeight - previousHeight;
if (currentHeight < previousHeight)
{
Physics.gravity = new Vector3(0, -25.0f, 0);
}
previousHeight = currentHeight;
}
void OnCollisionStay(Collision col)
{
//Resetting gravity after the cube hits ground.
if (col.gameObject.tag == "Cube")
{
Physics.gravity = new Vector3(0, -9.81F, 0);
}
}
}
Any help would be very much appreciated!