- Home /
Why isn't my character moving down?
Hi,
I'm creating a movement script for my player (2D project pixel art) and basically everything works as it should except for the up and down function.
When I press "W or the up key" my player goes up ... so + on y... But when I press "S or the down key" my player is also going up on y... which is weird.
I'm starting C# since I'm more of a designer so my code is probably longer than necessrary but for now I'm just trying to learn and fix my problems :-)
Thanks in advance!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float playerMovementSpeed = 3f;
private void FixedUpdate()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
if (h != 0f)
{
transform.Translate(new Vector2(h * playerMovementSpeed * Time.deltaTime, 0f));
} else if (v != 0f)
{
transform.Translate(new Vector2(v * 0f, playerMovementSpeed * Time.deltaTime));
}
}
}
Answer by Avinity · Jul 23, 2019 at 01:18 PM
I finaly found out.
my multiplier was on the X and not on Y.
Wrong code:
transform.Translate(new Vector2(v * 0f, playerMovementSpeed * Time.deltaTime));
Rewritten code:
transform.Translate(new Vector2(0f, v * playerMovementSpeed * Time.deltaTime));
Answer by I_Am_Err00r · Jul 23, 2019 at 12:50 PM
I found this online and based on what I see it looks legit, try something like this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Rigidbody2D body;
float horizontal;
float vertical;
public float runSpeed = 20.0f;
void Start ()
{
body = GetComponent<Rigidbody>();
}
void Update ()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}
}
I don't have a compiler, haven't tested this, but this looks like something I would start with and customize from there.
Answer by Avinity · Jul 23, 2019 at 01:01 PM
I've put it in, added a Rigidbody to refer to but it isn't working at all.
second thing with this script. I don't want to allow the player to move diagonal and I wouldn't know how to change that in that script.
Thanks for the option but I think this isn't the solution to the problem. I'm not even sure if the problem is in the script at all because I wouldn't know where it would be.