- Home /
Unity Car Accelerometer
Hello everyone!!! I'm new to Unity. I have a problem, why when I launch a game on android the car isn't work with accelerometer(I mean when I tap on screen and rotate car isn't drive) ? The car spins along the axis z. Please help me, what's the problem? I have the following code in C #:
using System.Collections;
using System.Collections.Generic; using UnityEngine;
public class CarController : MonoBehaviour {
public float speed = 1500f;
public float rotationSpeed = 15f;
public WheelJoint2D backWheel;
public WheelJoint2D frontWheel;
public Rigidbody2D rb;
private float movement = 0f;
private float rotation = 0f;
//private Vectro3 move;
public Vector2 touchPosition;
public double halfScreen;
void Update()
{
//movement = -Input.GetAxisRaw("Vertical") * speed;
//rotation = Input.GetAxisRaw("Horizontal");
movement = -Input.acceleration.x * speed;
rotation = Input.acceleration.z;
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Stationary)
{
touchPosition = Input.GetTouch(0).position;
halfScreen = Screen.width / 2.0;
}
}
void FixedUpdate()
{
if (movement == 0f)
{
backWheel.useMotor = false;
frontWheel.useMotor = false;
}
else
{
if (touchPosition.x > halfScreen)
{
backWheel.useMotor = true;
frontWheel.useMotor = true;
JointMotor2D motor = new JointMotor2D { motorSpeed = movement, maxMotorTorque = 10000 };
backWheel.motor = motor;
frontWheel.motor = motor;
}
// move = new Vector3(Input.acceleration.x, 0.0f, Input.acceleration.y);
}
//transform.Rotate(0, 0, -movement * speed);
rb.AddTorque(-rotation * rotationSpeed * Time.fixedDeltaTime);
}
}
Thanks for your help in advance!
Comment
Your answer
Follow this Question
Related Questions
Move to touch position 1 Answer
Lerp not working 1 Answer
How to aim at the point you're touching? 1 Answer
How to make your object follow your touch position faster or instantaneously??? 2 Answers
Move object by touch input 5 Answers