Can someone help me with this script...

So i wanted to make a FPS movement script, but the character always moves forward even if i look backward.(sorry for my bad english, and ik this code is a mess but i will fix that later)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player : MonoBehaviour
{
    private float Speed = 3.0f;

    public string MoveLeft = "a";
    public string MoveRight = "d";
    public string MoveForward = "w";
    public string MoveBack = "s";

    private float JumpVelocity = 3.0f;

    public string JumpKey = "space";

    public Camera Cam;

    private float SpeedH = 2.0f;
    private float SpeedV = 2.0f;

    private float Yaw = 0.0f;
    private float Pitch = 0.0f;

    void Update()
    {
        CameraMoveMent();
        Jumpy();
        MoveMent();

    }

    void CameraMoveMent()
    {
        Yaw += SpeedH * Input.GetAxis("Mouse X");
        Pitch -= SpeedV * Input.GetAxis("Mouse Y");

        if (Pitch >= 90)
        {
            Pitch = 90;
        }
        if (Pitch <= -90)
        {
            Pitch = -90;
        }

        Cam.transform.eulerAngles = new Vector3(Pitch, Yaw, 0.0f);
    }

    void Jumpy()
    {
        if(Input.GetKey(JumpKey))
        {
            transform.position += Vector3.up * JumpVelocity * Time.deltaTime;
        }
    }

    void MoveMent()
    {
        if (Input.GetKey(MoveLeft))
        {
            transform.position = transform.position + Vector3.left * Speed * Time.deltaTime;
        }

        if (Input.GetKey(MoveRight))
        {
            transform.position = transform.position + Vector3.right * Speed * Time.deltaTime;
        }

        if (Input.GetKey(MoveForward))
        {
            transform.position = transform.position + Vector3.forward * Speed * Time.deltaTime;
        }

        if (Input.GetKey(MoveBack))
        {
            transform.position = transform.position + Vector3.back * Speed * Time.deltaTime;
        }
    }
}

2 Answers

2

@Casiell 's solution is correct, but does not work in your case because you’re acting upon 2 objects here. You move the player GameObject and you rotate the camera.
You should either

  • use cam.transform.foward
  • or actually rotate the player and have the camera follow the position and rotation of the player.

Thank you. it worked.

In your MoveMent() method you are using Vector3.forward. Those are constant values and they will never change, no matter how your character is rotated. What you want to do is use transform.forward. This will take your character rotation into account. The same goes for left/right movement.

Note that there is no transform.back or transform.left. To get those you just multiply transform.forward/right by -1

Thank you for your quick reply. Sadly it didn't work i tested it but the problem stayed the same.My char still moves forward when i look backward.