Movement based on Camera direction help. C#

Hello, I was hoping to ask a question as I am a little bit stuck on coding movement for my Player.
First off, I have currently a somewhat working build of movement for a Third Person camera, using transform.Translate and a Orbital camera system I have made it that it can move around using the Cameras transform as the direction. However for moving forward and backward (using Vector3.forward) he bumps/hops a little bit across the ground, Til I figured out that its calculating the currentY of the Cameras orbital movements. Its fine for the Left and Right movement (Essentially strafeing). But since I am new to Unity (I do have coding experience from GML from Game Maker and dabbled a bit in 3D from there I know somewhat what to do) I was wondering if theres any particular way of making the Player object move forward and backwards by using the Cameras currentX rather than both Y and X. Because I realize the term for transform is using all of its positioning where it is in the world. Again, New to Unity so any clarification would be nice. And due to saying that Id like to keep the coding maybe somewhat simple and broken down so I can learn as I go along with it. Ill post what I have here currently so that people may take a look at what I have.

Player Code:

using UnityEngine;
using System.Collections;

public class MovementPlayer : MonoBehaviour {

    //Global VAR's
    public static int HP = 100;
    public static int MAXHP = 100;
    public static int STAM = 100;
    public static int MAXSTAM = 100;


    //Movement VAR's
    public float MoveSpeed = 4f;
    public float TurnSpeed = 50.0f;
    public int Can_Run = 0;
    public int Ground = 0;
    public int Gravity = 5;
    private float VertVelocity;


    private Vector3 FORWARD;
    private Vector3 BACK;
    private Vector3 RIGHT;
    private Vector3 LEFT;

    //public Rigidbody PlayerRBody;
    public CharacterController PlayerController;

    // Use this for initialization
    void Start () {
    //    PlayerRBody = GetComponent<Rigidbody> ();
        PlayerController = GetComponent<CharacterController> ();

        //Movement Shit.
        FORWARD = MoveSpeed * Vector3.forward;
        BACK = MoveSpeed * Vector3.back;
        RIGHT = MoveSpeed * Vector3.right;
        LEFT = MoveSpeed * Vector3.left;
    }

    // Update is called once per frame
    void FixedUpdate () {
        Movement ();
        Grav ();


    }





    void Movement() {

        //If we're on the Ground, react accordingly
        if (Ground == 1) {
            //Forward
            if (Input.GetAxis ("Vertical") > 0) {
                transform.Translate (FORWARD * Time.deltaTime, Camera.main.transform);
//                transform.Rotate (0,TurnSpeed * Time.deltaTime,0);
            }
            //Backwards
            if (Input.GetAxis ("Vertical") < 0) {
                transform.Translate (BACK * Time.deltaTime, Camera.main.transform);

            }
            //Right
            if (Input.GetAxis ("Horizontal") > 0) {
                transform.Translate (RIGHT * Time.deltaTime, Camera.main.transform);

            }
            //Left
            if (Input.GetAxis ("Horizontal") < 0) {
                transform.Translate (LEFT * Time.deltaTime, Camera.main.transform);

            }
      
        }
    }
      


    //Gravity Control.
    void Grav() {
        if (PlayerController.isGrounded) {
            VertVelocity = -Gravity * Time.deltaTime;
            Ground = 1;
            Debug.Log ("Landed");
        } else {
                VertVelocity -= Gravity/4 * Time.deltaTime;
                Debug.Log ("In Air");
                Ground = 0;
        }

        Vector3 MoveVector = new Vector3 (0, VertVelocity, 0);
        PlayerController.Move (MoveVector * Time.deltaTime);
    }
      
}

Camera Code:

using UnityEngine;
using System.Collections;

public class ThirdPersonCAMScript : MonoBehaviour {

    private const float Y_ANGLE_MIN = 0.0f;
    private const float Y_ANGLE_MAX = 30.0f;

    public Transform lookAt;
    public Transform camTransform;

    private Camera cam;

    private float distance = 10.0f;
    public float currentX = 0.0f;
    public float currentY = 0.0f;
    private float sensitivityX = 4.0f;
    private float sensitivityY = 1.0f;

    // Use this for initialization
    void Start () {
        camTransform = transform;
        cam = Camera.main;
    }
  
    // Update is called once per frame
    void Update () {
        currentX += Input.GetAxis ("Mouse X");
        currentY += Input.GetAxis ("Mouse Y");

        currentY = Mathf.Clamp (currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);

    }

    // Update is called once per frame
    void LateUpdate () {
        Vector3 dir = new Vector3 (0, 0, -distance);
        Quaternion rotation = Quaternion.Euler (currentY, currentX, 0);
        camTransform.position = lookAt.position + rotation * dir;
        camTransform.LookAt(lookAt.position);

    }

}

Thanks in advance for any help what so ever!
~Zak!

Hi, and welcome to Unity :slight_smile:
First off, please take a moment to look at this page : Using code tags properly - Unity Engine - Unity Discussions
It will show you how to update your post (and for any future posts), about how to post your code more nicely.

With regard to your camera question, I’d have to say/ask if you plan to incorporate much more with the camera/player movement? You might benefit from looking over the 3rd person controller and the camera rig (and whatever scripts come with that: prevent wall clip, for instance).

Personally, I found the design of the Camera Rig (in the standard assets) to be quite useful – not only because it works well, but it gave me an appreciation for why it works, too :slight_smile: (it uses 3 parts to handle the rotation/camera).
That would tie into your question, I believe… One ‘parent’ object does the X/Y axis, its child does the other, and the 3rd child (the camera itself) could be what you use for your forward. =)

Hope that helps. Enjoy yourself. :slight_smile:

Thanks, And Ill be sure to use that in the future. xD

I tried looking at the standard assets but most of the code and terms ended up confusing me, Which is why I wanted to try and look up most things from the manual and figure out what they do and try and do it from scratch as I find that being an easier way for me to learn how to do most things, if not just general help in general to show me what and where Ive gone wrong. lol

What I hope to do is just have a basic 3D camera that targets the player and the Player moves in the direction the Cameras facing with no issues. However for future stuff I wouldnt mind trying to do a lock on feature for the camera so it locks onto a target while having the Player still in view, kinda like Zeldas Z Targeting mechanic, But for now I just want to keep it simple for now so that way I can learn the ropes as I seem to be pretty adaptable with figuring out stuff given time. Just needed the extra know how for the lack of a better word on getting it to move forward without the bumps but the best thing Ive managed to do is more so just a free flying camera if I didnt have the gravity going xDD

Thanks for the advice though, but other than that theres nothing that I would be able to use to make it check for the currentX for the camera rather than just the entire transform? Nothing like: “Camera.main.currentX” or as new variable that takes the value from the other script and do it that way?

Again, Thank you kindly for replying.

Ya, no problem. I love learning and trying stuff, too :slight_smile:

Honestly, I think you’ll appreciate the camera rig a lot, though. I mean even if you don’t use its code or even the prefab, – just the concept I described in my previous post will be very helpful for you.
And yes, you can get the camera’s forward (i’m not entirely clear on what you mean by ‘X’ only).
If you have the camera referenced, “cam.transform.forward” is its local forward direction.

Okay, sorry and about the ‘bumps’ ? hm. I’m not 100% on that… It’s a good idea to put camera updates in the “LateUpdate()” method (if it’s that kind of bumpy issue…). If it’s something else, could you describe? Are you going in the air, do you mean?

Edit: Oops - looked at your code, you are using late update… so you probably mean something else :wink:

Yeah, What I described for how Im guessing I coded it is, Say if you coded a flying sim for an Aeroplane. Since it moves depending on the cameras overall direction it’ll try and move downwards and upwards depending on if the Camera is higher or lower than the player, but since I have gravity and collisions on the Player controller itself it’ll just bump around because it cannot go through it to fly around. If that makes sense. So its that kind of bumpiness I’m dealing with, hence why I want to know whats the best way to lose the bumping around on the ground and move forward depending where the camera is. If you get what I’m saying? I know, it sounds a bit hard to understand but thats the best way to describe it without somebody putting the code into a project themselves and experience the problem itself. ^^’

I just want to say also that the Camera is fine, its more so the Player movement script that I need the help translating the movement onto. Sorry if I wasnt clear about that to begin with ^^’

Try this package I attached :slight_smile:

If for any reason you can’t use the package I can just copy the scripts here, instead.

3217168–246456–PackageForCharCam.unitypackage (11.2 KB)

Thank you for doing that but its kinda not what I wanted. ^^’ Hopefully if I show you an example of what Im trying to aim for that might be better because you may have misunderstood me.

Hopefully this clarifies. Very Very sorry for messing you around and wasting your time >3<’

Okay… What is it that I’m missing here that is different between the package and the video? Please spell it out for me… lol I watched it & it looks very similar
(obviously not including the capsule vs a finished game ;))

and it’s no prob… I mean… I misunderstood something. Just not 100% sure what :slight_smile:

Well, Its kinda just still doing the samething, Just without the gravity. So its going in the forward direction. What I just want, is that the Player should move depending which way the camera is facing, But I dont want it to bump along the ground, I want it to move smoothly along the ground and not bounce around without it being pushed out of the solid object its trying to get inside of. So basically no matter how high it is or how low in correlation to the Player I want it to move smoothly along the ground. If that makes sense? Essentially I dont want it to fly around.

If I have to draw up a diagram I can if that’ll help with understanding it. lol

Ya, no that makes sense…Did you open my package?

I know in the package (if you opened it and read the comment in one of the .cs files)… I disabled gravity, but that was just while I was testing to rule out my own issues. Obviously you can use gravity…

hm…When you say “don’t want it to fly around” - do you mean the camera or the person?
Because in the video, the camera can/does move (at least somewhat… I don’t know if those are its limits, or that’s all that was recorded).
Obviously, you don’t want the player to fly around… that shouldn’t be happening in the package I uploaded.

I dont want the person flying around. - And the bumping along the ground is still happening when the camera is higher or lower than the player. And Yes gravity is turned back on.

Ok, let me look at it again with the gravity on.
As for the person flying around – that is quite odd. I didn’t get any of that in my tests…

Ok – there was 1 variable unassigned (error in my editor). If you had that in yours, make sure you assigned the correct one.

I put gravity back on and everything is working… there’s no player flying, there’s no bouncing…
hmm… Question: Is your ‘ground’ bumpy??

No, its a flat sqaure. Default model of Unitys. Question, what did you assign each part for the Camera object? Maybe its different for me so I might as well check for that.

Well, make sure you disable any other camera you might have …

The camera should be like this:
– Camera Rig
– Camera Pivot
– Actual Camera

I have:
LookAt: Capsule(Player)
CamTransform: Main Camera
CAMPivot: Main Camera
CAM Rig: Main Camera.

I only have the Main Camera.

Ok. 1 step back here. Did you open the package I sent? :slight_smile:

It has a camera rig prefab in it.

Yes. - And I see it, But wont let me open it, How do I use it?

Oh ok… lol well you should have said that sooner. All this time I thought you were using it.
I’m not sure if you can drag & drop it in unity.

Go to Assets → Import package → Custom package and find it on your hard drive.

You did mean not sure how to open the package, right? Or just the camera?

Oh, Its already inside the Project file. Im just wondering how to stick it to where it needs to go, Since Unity wont let me get it onto an object or anything lol