- Home /
Question by
Poseidon1145 · Sep 17, 2017 at 01:17 AM ·
rotationjoystick
stay the rotation in character
Hi i have a problem, I create a script that when using the input of a joystick, where it pointed the joystick rotated the character and when you stop moving the joystick your rotation returned to 0
but I need to move the joystick and rotate the character to stop moving the joystick does not return to zero but is in its last rotation.
for example I moved the character to a rotation of 30 degrees and when releasing the joystick that is not returned to 0 but stays in 30
sorry for my english i used the Google Translate xD
wtf.png
(8.1 kB)
Comment
Answer by unit_nick · Sep 17, 2017 at 03:17 AM
/*
* To see this work just create a new project
* and attach this script to an empty game object
*/
using UnityEngine;
public class Setup : MonoBehaviour {
GameObject player;
public float horizontalSpeed = 1;
public float verticalSpeed = 1;
public bool returnRotation = false;
private float horizontal = 0;
private void Start()
{
GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
plane.name = "Plane";
plane.GetComponent<Renderer>().material.color = Color.black;
player = GameObject.CreatePrimitive(PrimitiveType.Capsule);
player.name = "Player";
player.transform.position += Vector3.back * 4f;
player.AddComponent<Rigidbody>().useGravity = true;
player.GetComponent<Rigidbody>().constraints = (RigidbodyConstraints)122;
GameObject visor = GameObject.CreatePrimitive(PrimitiveType.Cube);
visor.name = "Visor";
visor.transform.parent = player.transform;
visor.transform.localPosition = new Vector3(0f, 0.5f, 0.24f);
visor.transform.localScale = new Vector3(0.95f, 0.25f, 0.5f);
visor.GetComponent<Renderer>().material.color = Color.black;
}
private void Update()
{
float horizontalImpulse = Input.GetAxis("Horizontal");
if (horizontalImpulse > 0f)
{
horizontal += horizontalSpeed * Time.deltaTime * 100;
}
else if (horizontalImpulse < 0f)
{
horizontal -= horizontalSpeed * Time.deltaTime * 100;
}
else if (returnRotation)
{
float absValue = Mathf.Min(Mathf.Abs(horizontal), Mathf.Abs(horizontalSpeed * Time.deltaTime * 100));
horizontal -= absValue * Mathf.Sign(horizontal);
}
player.transform.localRotation = Quaternion.Euler(0, horizontal, 0);
player.transform.position += player.transform.forward * Input.GetAxis("Vertical") * verticalSpeed * Time.deltaTime;
}
}