- Home /
Mobile Movement won't work
Hello I have a script for my player's movement but for some reason it only works on PC. I tried SO many methods to make the player move on mobile (including joysticks, Raycasters and CrossPlatform) but nothing works. Here is my current script, would love if anybody could help me figure out why it won't work:
using System.Collections;
using System.Collections.Generic;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine;
public class Movement : MonoBehaviour
{
//variables
public Animator animator;
public float moveSpeed = 0.9f;
public GameObject character;
private Rigidbody2D characterBody;
private float ScreenWidth;
// Use this for initialization
void Start()
{
gameObject.tag = "Player";
ScreenWidth = Screen.width;
characterBody = character.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
int i = 0;
//loop over every touch found
while (i < Input.touchCount)
{
if (Input.GetTouch(i).position.x > ScreenWidth / 2)
{
//move right
RunCharacter(0f);
}
if (Input.GetTouch(i).position.x < ScreenWidth / 2)
{
//move left
RunCharacter(0f);
}
++i;
}
}
void FixedUpdate()
{
animator.SetFloat("Horizontal", CrossPlatformInputManager.GetAxis("Horizontal"));
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
#endif
}
private void RunCharacter(float horizontalInput)
{
//move player
//characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0f));
characterBody.velocity = new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0.0f);
//animator
if (CrossPlatformInputManager.GetAxisRaw("Horizontal") == 1 || CrossPlatformInputManager.GetAxisRaw("Horizontal") == -1)
{
animator.SetFloat("LastMove", CrossPlatformInputManager.GetAxisRaw("Horizontal"));
}
}
}
also note: this script used to work on my early drafts. Not sure what changed since I only added an animator to it.
Answer by Llama_w_2Ls · Nov 21, 2020 at 07:01 PM
In both your touch inputs (in your update), you call the function RunCharacter(0f). This takes in the parameter HorizontalInput and multiplies the characterBody.velocity by it and other factors. If the HorizontalInput is 0, your character will never move!! @TheBloop
Also I didnt know you could do ++i
instead of i++
to increment by 1.
Yup, you were right! feel kinda silly for just missing that. Thank you! However now the animator won't work, not sure how to fix it...
Try not to use animator.SetFloat
, instead you can just make the animator play an animation clip like animator.Play("AnimationClipName")
. Sorry i guess. Cant really help much
Your answer
![](https://koobas.hobune.stream/wayback/20220613020218im_/https://answers.unity.com/themes/thub/images/avi.jpg)