Question by
DerAntagonist · Aug 21, 2018 at 09:04 AM ·
2dmovementtilemapcontrol
Don't moving diagonal
I am trying to disable the possibility of my character to move diagonally when im hitting w and d at the keyboard. I have a 2D Topdown Tilemap. I think it could be done with private bool LockVertical/Horizontal but I have no idea how. This is the code to make my player move:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float MoveSpeed;
private bool LockHorizontal = true;
private bool LockVertical = true;
private Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if(Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f )
{
transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * MoveSpeed * Time.deltaTime, 0f, 0f));
}
if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f)
{
transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") * MoveSpeed * Time.deltaTime, 0f));
}
anim.SetFloat("MoveX", Input.GetAxisRaw("Horizontal"));
anim.SetFloat("MoveY", Input.GetAxisRaw("Vertical"));
}
}
Comment
Best Answer
Answer by Hellium · Aug 21, 2018 at 09:39 AM
Following code not tested:
private const horizontalAxisName = "Horizontal";
private const verticalAxisName = "Vertical";
private float horizontal ;
private float vertical ;
void Update ()
{
Vector3 translation = Vector3.zero ;
// Get vertical input only if the player does not already move horizontally
if( horizontal <= 0.5f & horizontal >= -0.5f )
vertical = Input.GetAxisRaw( verticalAxisName ) ;
// Get horizontal input only if the player does not already move vertically
if( vertical <= 0.5f & vertical >= -0.5f )
horizontal = Input.GetAxisRaw( horizontalAxisName ) ;
// Translate horizontally only if the input is high enough
if( horizontal > 0.5f || horizontal < -0.5f )
translation.x = horizontal ;
// Translate vertically only if the input is high enough
if( vertical > 0.5f || vertical < -0.5f )
translation.y = vertical ;
transform.Translate(translation);
anim.SetFloat("MoveX", horizontal);
anim.SetFloat("MoveY", vertical);
}