- Home /
Question by
MuZzASA · Jan 30, 2020 at 06:21 PM ·
2dmovement2d gamecontrollertop down shooter
Unity2D Space shooter rotation resetting when analogue stick input has ended
So I am new to unity and scripting, creating my first project to learn, so noob question incoming.
I am trying to get my player spaceship rotating based on the right analogue stick input but when the the player isn't doing anything the player ship's rotation just resets to it's original position. I want the ship to have smooth 360 movement.
Below is my movement script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class TwinStickMovement : MonoBehaviour
{
PlayerControls controls;
Vector2 move;
Vector2 rotate;
void Awake()
{
controls = new PlayerControls();
controls.Gameplay.Movement.performed += ctx => move = ctx.ReadValue<Vector2>();
controls.Gameplay.Movement.canceled += ctx => move = Vector2.zero;
controls.Gameplay.Rotation.performed += ctx => rotate = ctx.ReadValue<Vector2>();
controls.Gameplay.Rotation.canceled += ctx => rotate = Vector2.zero;
}
void Update()
{
Vector2 m = new Vector2(move.x, move.y) * 10f * Time.deltaTime;
transform.Translate(m, Space.World);
Vector2 r = new Vector2(rotate.x, rotate.y) * 100f * Time.deltaTime;
this.transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, Mathf.Atan2(r.y, r.x) * Mathf.Rad2Deg), Time.deltaTime * 2);
}
void OnEnable()
{
controls.Gameplay.Enable();
}
void OnDisable()
{
controls.Gameplay.Disable();
}
}
Comment
Answer by LeFlop2001 · Jan 30, 2020 at 09:53 PM
I really don't know what you did but heres my approach do the movement and rotation .If you have any question ,im happy to answer.
P.S. i can also explain you how to smooth out the rotation if you want
using UnityEngine;
public class Test : MonoBehaviour
{
public float movementSpeed;
void Update()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
if (Mathf.Abs(x) > 0.01f || Mathf.Abs(y) > 0.01f)
{
transform.up = new Vector2(x,y).normalized;
}
transform.position += (Vector3.up * y + Vector3.right * x) * Time.deltaTime * movementSpeed;
}
}
thanks for the reply. I have good rotation with left stick but no movement on the y or x axis.