- Home /
Why is my character controller not working?
Hello there im trying to make a small endlessrunner for mobile phones and tried making the character controller, but it doesnt work for touch controlls(hes just not moving). Hope you can help me? My character controller(note that he is supposed to move freely to the left and right):
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerTouchMovement : MonoBehaviour { public Rigidbody2D rb; Vector2 movement; public float moveSpeed = 12.5f;
private PlayerTouchMovement()
{
movement.y = 0f;
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
Touch tipp = Input.GetTouch(0);
movement = Camera.main.ScreenToWorldPoint(tipp.position);
if(movement.x > 0)
{
Debug.Log("Tipp ist positiv");
movement.x = 1f;
}
if(movement.x < 0)
{
Debug.Log("Tipp ist negativ");
movement.x = -1f;
}
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + (movement * moveSpeed * Time.fixedDeltaTime));
}
}
Btw I´m on unity remote 5 on android if this helps.
Just a quick check: is your rigidbody set to kinematic? Rigidbody2D.$$anonymous$$ovePosition is only reliable on kinematric rididbodies
Yes it is. Funny thing if i change the x axis checking part with GetAxisRaw("horizontal") i can move him on keyboard.
Answer by lukiwasDevStuff · May 21, 2020 at 04:31 PM
I managed to get it working with that, maybe it was stopped by another part of another script. But for some reason it´s slow and when you type to quickly it gets buggy.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerTouchMovement : MonoBehaviour { public Rigidbody2D rb; Vector2 tippPosition; public float MoveSpeed; Vector2 tippSpeicher;
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
Debug.Log("Tippen wird registriert");
Touch tipp = Input.GetTouch(0);
tippPosition = Camera.main.ScreenToWorldPoint(tipp.position);
if (tippPosition.x > 0)
{
Debug.Log("Tipp ist positiv");
tippSpeicher.x = 1;
tippSpeicher.y = 0;
}
if (tippPosition.x < 0)
{
Debug.Log("Tipp ist negativ");
tippSpeicher.x = -1;
tippSpeicher.y = 0;
}
}
else
{
tippSpeicher.x = 0;
tippSpeicher.y = 0;
rb.position = rb.position;
}
if (Input.touchCount < 0)
{
tippSpeicher.x = 0;
tippSpeicher.y = 0;
rb.position = rb.position;
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + tippSpeicher * MoveSpeed * Time.deltaTime);
}
}