Hi, I am following a Lynda course(Advance 2D Platformer). In the first lesson, they are creating a custom made input manager. I attached the code. My questions are, What is the main purpose of using this? Can’t we use the simple method (Input.GetAxis())? Explain me please. I just learned some basic stuffs and moved on to this and this is just confusing me. Sorry for my poor English.
InputState.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ButtonState{
public bool value;
public float holdTime=0;
}
public class InputStates : MonoBehaviour {
private Dictionary<Buttons, ButtonState> buttonStates = new Dictionary<Buttons,ButtonState>();
public void SetButtonValue(Buttons key, bool value){
if(!buttonStates.ContainsKey(key))
buttonStates.Add(key,new ButtonState());
var state = buttonStates [key];
if(state.value && !value){
Debug.Log("Button "+key+ " release "+ state.holdTime);
state.holdTime = 0;
}else if(state.value && value){
state.holdTime += Time.deltaTime;
Debug.Log("Button "+key+ " down "+ state.holdTime);
}
state.value = value;
}
public bool GetButtonValue(Buttons key){
if(buttonStates.ContainsKey(key))
return buttonStates[key].value;
else
return false;
}
InputManager
using UnityEngine;
using System.Collections;
public enum Buttons{
Right,
Left,
}
public enum Conditions{
GreaterThan,
LessThan
}
[System.Serializable]
public class InputAxisState{
public string axisName;
public float offValue;
public Buttons button;
public Conditions condition;
public bool value{
get{
var val = Input.GetAxis(axisName);
switch(condition){
case Conditions.GreaterThan:
return val > offValue;
case Conditions.LessThan:
return val < offValue;
}
return false;
}
}
}
public class InputManager : MonoBehaviour {
public InputAxisState[] inputs;
public InputStates inputState;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
foreach(var input in inputs){
inputState.SetButtonValue(input.button, input.value);
}
}
}
SimpleMovement.cs
using UnityEngine;
using System.Collections;
public class SImpleMovement : MonoBehaviour {
public float speed;
public Buttons[] input;
private Rigidbody2D body2D;
private InputStates inputState;
// Use this for initialization
void Start () {
body2D = GetComponent<Rigidbody2D>();
inputState = GetComponent<InputStates>();
}
// Update is called once per frame
void Update () {
var right = inputState.GetButtonValue(input[0]);
var left = inputState.GetButtonValue(input[1]);
var velX = speed;
if(right || left){
velX *= left ? -1 : 1;
}else{
velX = 0;
}
body2D.velocity = new Vector2(velX, body2D.velocity.y);
}
}