- Home /
Player Movement when phone shakes
So, I was trying to do a test where my game character can be moved using a joystick or a "shake" on the phone (the idea is that when the player walks around, the phone had a tilt and then, it's counted as a step in game). Maybe you can help me with the code. This code's objective is getting: 1 - The accelerometer input in y axis; 2 - The Joystick values; 3 - What I call "shaking routine"
So, the shaking routine happens when the accelerometer goes from the "low range" to the "high range" and then come back to the "low range". I made some tests and came with a low range from >0 and <1, the high range is any value >1 for the accelerometer input. For that, I've created a while structure, where it keeps comparing values from the accelerometer until finding the sequence that represents a shake.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
protected Joystick joystick;
public CharacterController controller;
// Start is called before the first frame update
void Start()
{
joystick = FindObjectOfType<Joystick>();
}
// Update is called once per frame
void Update()
{
float accel;
bool isShaking;
int low;
int high;
accel = -Input.acceleration.y;
low = 0;
high = 0;
Vector3 move = transform.right * joystick.Horizontal;
isShaking = false;
while (isShaking == false)
{
// Detect first movement
if (accel < 1 && accel > 0) low++;
// Detect second movement (only if first movement was detected)
if (accel > 1 && low == 1) high++;
// Detect a sequency of 1 low, 1 high and 1 low happen (2 low and 1 high)
if (low == 2 && high == 1) isShaking = true;
// If there was no sequence, do normal playermove
move += transform.forward * joystick.Vertical;
controller.Move(move * 10f * Time.deltaTime);
}
// Only if detected shaking sequence
move += transform.forward * 0.8f;
controller.Move(move * 10f * Time.deltaTime);
}
}
But when I run this code, the engine crashes. What's wrong?