- Home /
Moving a 2D character along the X and Z axis only.
Hello,
I'm trying to build a game using 2D sprites in 3D environments. Visually it'd kinda look like Paper Mario games but with pixel characters instead of hand-drawn art.
I'm working on my Player characters movement and am trying to get him to move along the X and Z-axis. I can get him to move left and right along the X-axis fine but he'll only move forward, away from the camera and not towards it/the player on the Z (the S key or Down Arrow Key). If I press the S key or Down Arrow Key, it still wants to keep moving forward/up on the Z-axis. Any help is appreciated.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour {
public float moveSpeed;
// Start is called before the first frame update
void Start() {
}
// 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(Input.GetAxisRaw("Vertical") * moveSpeed * 0f, 0f, Time.deltaTime));
}
}
}
Other info: my Player has a Rigidbody not using Gravity but Kinematic instead and Discrete Collision Detection. He also has a Box Collider that helps keep him from falling through the Ground Object. Hope this is enough information. Thanks again.
Answer by dan_wipf · Jan 15, 2019 at 04:48 AM
well you messed something up inside the the transform.Translate part. you twice move on the x axis and on vertical movement you have Time.delta on the z axis.
just to clarify : your Vector3(horizontalAxis,yAxis,verticalAxis) part of the code is this
horizontal = Vector3 (code, 0f, 0f) => correct
vertical = Vector3 (code, 0f, time.deltatime) => should be Vector3(0f, 0f, code)
so I'd recommend you following:
if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
{
float hori = Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime;
transform.Translate(new Vector3(hori, 0f, 0f));
}
if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f)
{
float vert = Input.GetAxisRaw("Vertical") * moveSpeed * Time.deltaTime;
transform.Translate(new Vector3( 0f, 0f, vert));
}
untested Code, but I guess this is the correct approach of your code
This worked thank you so much for taking the time to help!