- Home /
How to move the character to bottom left/right?
Heading
Hi! I'm working on a 2D game and i want my character to move to the bottom left or right direction. I already made two buttons, but when i press them, my character goes only to the right or left.
Here the code i am using to make my character move with touchscreen buttons:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Movement : MonoBehaviour { public float moveSpeed = 300; public GameObject character;
private Rigidbody2D characterBody;
private float ScreenWidth;
// Use this for initialization
void Start () {
ScreenWidth = Screen.width;
characterBody = character.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
int i = 0;
//loop over every touch
while (i < Input.touchCount) {
if (Input.GetTouch (i).position.x > ScreenWidth / 2) {
//move right
RunCharacter (1.0f);
}
if (Input.GetTouch (i).position.x < ScreenWidth / 2) {
//move left
RunCharacter (-1.0f);
}
++i;
}
}
void FixedUpdate(){
#if UNITY_EDITOR
RunCharacter(Input.GetAxis("Horizontal"));
#endif
}
private void RunCharacter(float horizontalInput){
//move player
characterBody.transform.Translate(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 1));
}
}
Hi @JustSova, drop some code, above, then people will be able to help. Will be more accurate than guessing.
Your answer
Follow this Question
Related Questions
2D Zig-zag movement and rotation 1 Answer
[2D] Moving the player 1 tile at a time using rigidbody movement 0 Answers
Sprite will not roate when arrow keys are pressed 2 Answers
2D game with two point perspective and distortion? 1 Answer
2D player keeps getting dragged to the left for some reason. 0 Answers