2D movement... again...

Tried to look it up on your forums, I’ve stolen from here, stolen from there, this is where I’m left at:

using UnityEngine;
using System.Collections;

public class playerMovement : MonoBehaviour {
    public float movementSpeed_MOD;      // set as 1 in Editor
    public float rotationSpeed_MOD;     // set as 1 in Editor

    Transform selfTransform;
    Vector3 selfPosition;
    Vector3 selfRotation;
    float selfAngle;

    void Start() {
        selfTransform = transform;
        selfPosition = selfTransform.position;
        selfRotation = selfTransform.rotation.eulerAngles;
    }

    void FixedUpdate() {
        selfAngle = selfTransform.eulerAngles.magnitude * Mathf.Deg2Rad;

        if (Input.GetKey (KeyCode.RightArrow)) {
            selfRotation.z -= rotationSpeed_MOD;
        }
        if (Input.GetKey (KeyCode.LeftArrow)) {
            selfRotation.z += rotationSpeed_MOD;
        }

        if (Input.GetKey (KeyCode.UpArrow)) {
          
            selfPosition.x += (Mathf.Cos(selfAngle) * movementSpeed_MOD) * Time.deltaTime;
            selfPosition.z += (Mathf.Sin(selfAngle) * movementSpeed_MOD) * Time.deltaTime;
        }
        if (Input.GetKey (KeyCode.DownArrow)) {
            selfPosition.x -= Mathf.Cos(selfAngle) * Time.deltaTime;
            selfPosition.z -= Mathf.Sin(selfAngle) * Time.deltaTime;  
        }

        selfTransform.position = selfPosition;
        selfTransform.rotation = Quaternion.Euler(selfRotation);
      
    }
}

I’ve attached this script to a player, which is an image, but the image makes strange movements. When you tell it to go forward it goes forward and slightly to the side. When you tell it to move left, it will turn right. I tried changing the sides (selfRotation.z += or -=). But I can’t get Unity to react, whenever I change it, it just switches sides entirely including the interaction, leaving it exactly same.

This is top-down game, where player can move their character forwards and backwards, and turn left and right with arrows.

Yeah, this code doesn’t make much sense. You’re moving in X and Z, which implies that your sprite is in the XZ plane. But then you’re rotating around Z… that makes no sense. If you’re in the XZ plane, you should be rotating around Y. (And the more usual 2D setup is to have your sprites in the XY plane, and rotate around Z.)

So, why don’t you start by figuring out exactly what plane your sprites are in. And then you should know what you want to rotate around.

Also, if your sprites are set up correctly, you don’t need to do any trigonometry to move around. You can instead just to transform.Translate(transform.forward * speed * Time.deltaTime) to move forward, and similar for moving backward.

HTH,

  • Joe
1 Like