- Home /
Help with topdown movement in Unity2d?
So, I have looked over the internet for a bit now, yet everything I try doesn't work. I put a movement script I have from a platformer onto the player, but I can only move it left and right. I am gonna post my code below, but my question is how to make it move up and down? Thanks for any help!
using UnityEngine;
using System.Collections;
public class MoveTopDown : MonoBehaviour {
public float speed =1.0f;
public string axisName = "Horizontal";
// Use this for initialization
void Start () {
}
void Update ()
{
}
// Update is called once per frame
void FixedUpdate () {
if (Input.GetAxis (axisName) > 0)
{
Vector3 newScale = transform.localScale;
newScale.y = 1.0f;
newScale.x = 1.0f;
transform.localScale = newScale;
}
else if (Input.GetAxis (axisName) < 0)
{
Vector3 newScale =transform.localScale;
newScale.x = 1.0f;
transform.localScale = newScale;
}
transform.position += transform.right * Input.GetAxis (axisName) * speed * Time.deltaTime;
}
}
Answer by robertbu · Jul 15, 2014 at 10:17 PM
You need to add a second axisName at the top of the file:
public string axisName2 = "Vertical";
Then you need to insert this at line 40:
transform.position += transform.up * Input.GetAxis(axisName2) * speed * Time.deltaTime;
Thanks, it sort of works, but it doesn't. It is just going up in down, in other words, just the y axis is moving. I need to be able to move the z axis. Any idea on how to do that?
If you have oriented your camera to look down the 'y' axis for your top-down implementation, just change 'transform.up' to 'transform.forward':
transform.position += transform.forward * Input.GetAxis(axisName2) * speed * Time.deltaTime;