- Home /
I need help with a Controller on a 2D Game for Android with horizontal movement
Hello, I am trying to implement horizontal movement of my main character in the game. I use the Axis Touch Button script to move the player and this script for the Player:
using System.Collections;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Player : MonoBehaviour {
float directionX;
public float speed = 15f;
public float mapWidth = 5f;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate ()
{
directionX = CrossPlatformInputManager.GetAxis("Horizontal") * Time.fixedDeltaTime * speed;
Vector2 newPosition = rb.position + Vector2.right * directionX;
newPosition.x = Mathf.Clamp(newPosition.x, -mapWidth, mapWidth);
rb.MovePosition(newPosition);
The problem is when I move the player left or right (by pressing left or right button) it keeps moving slowly to the same direction (after I have finished pressing that button) and it does not stop until I press the button for opposite direction.
Answer by Horschty · Jun 15, 2018 at 05:43 PM
Maybe it has something to do with input smoothing?
Edit -> Project Settings -> Input -> Axes -> Horizontal.
Try adjusting Gravity, Dead and Sensitivity. The Gravity setting for instance controls how much it slows down over time. If it's 0 it won't slow down and keep going forever. It works for me if I set it to: Gravity 3, Dead 0.001, Sensitivity 3.
Alternatively you could use GetAxisRaw instead of GetAxis (assuming CrossPlatformInputManager has the same methods as the normal Input class). That doesn't use smoothing.
Your answer
Follow this Question
Related Questions
How to play animations on entering a trigger and pressing a button? (2D) 1 Answer
New input system controller stops detecting on fully pressed trigger? 0 Answers
Double tap mechanics and axis inputs 3 Answers
Maintaining Run on direction change (double tap using GetAxis) 0 Answers
2D Platformer - Action When Key Is Pressed During Collision C# 0 Answers