Search Unity

Movement based on Camera direction help. C#

Discussion in 'Scripting' started by TheDevilsHitman, Sep 11, 2017.

  1. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    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:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MovementPlayer : MonoBehaviour {
    5.  
    6.     //Global VAR's
    7.     public static int HP = 100;
    8.     public static int MAXHP = 100;
    9.     public static int STAM = 100;
    10.     public static int MAXSTAM = 100;
    11.  
    12.  
    13.     //Movement VAR's
    14.     public float MoveSpeed = 4f;
    15.     public float TurnSpeed = 50.0f;
    16.     public int Can_Run = 0;
    17.     public int Ground = 0;
    18.     public int Gravity = 5;
    19.     private float VertVelocity;
    20.  
    21.  
    22.     private Vector3 FORWARD;
    23.     private Vector3 BACK;
    24.     private Vector3 RIGHT;
    25.     private Vector3 LEFT;
    26.  
    27.     //public Rigidbody PlayerRBody;
    28.     public CharacterController PlayerController;
    29.  
    30.     // Use this for initialization
    31.     void Start () {
    32.     //    PlayerRBody = GetComponent<Rigidbody> ();
    33.         PlayerController = GetComponent<CharacterController> ();
    34.  
    35.         //Movement S***.
    36.         FORWARD = MoveSpeed * Vector3.forward;
    37.         BACK = MoveSpeed * Vector3.back;
    38.         RIGHT = MoveSpeed * Vector3.right;
    39.         LEFT = MoveSpeed * Vector3.left;
    40.     }
    41.  
    42.     // Update is called once per frame
    43.     void FixedUpdate () {
    44.         Movement ();
    45.         Grav ();
    46.  
    47.  
    48.     }
    49.  
    50.  
    51.  
    52.  
    53.  
    54.     void Movement() {
    55.  
    56.         //If we're on the Ground, react accordingly
    57.         if (Ground == 1) {
    58.             //Forward
    59.             if (Input.GetAxis ("Vertical") > 0) {
    60.                 transform.Translate (FORWARD * Time.deltaTime, Camera.main.transform);
    61. //                transform.Rotate (0,TurnSpeed * Time.deltaTime,0);
    62.             }
    63.             //Backwards
    64.             if (Input.GetAxis ("Vertical") < 0) {
    65.                 transform.Translate (BACK * Time.deltaTime, Camera.main.transform);
    66.  
    67.             }
    68.             //Right
    69.             if (Input.GetAxis ("Horizontal") > 0) {
    70.                 transform.Translate (RIGHT * Time.deltaTime, Camera.main.transform);
    71.  
    72.             }
    73.             //Left
    74.             if (Input.GetAxis ("Horizontal") < 0) {
    75.                 transform.Translate (LEFT * Time.deltaTime, Camera.main.transform);
    76.  
    77.             }
    78.      
    79.         }
    80.     }
    81.      
    82.  
    83.  
    84.     //Gravity Control.
    85.     void Grav() {
    86.         if (PlayerController.isGrounded) {
    87.             VertVelocity = -Gravity * Time.deltaTime;
    88.             Ground = 1;
    89.             Debug.Log ("Landed");
    90.         } else {
    91.                 VertVelocity -= Gravity/4 * Time.deltaTime;
    92.                 Debug.Log ("In Air");
    93.                 Ground = 0;
    94.         }
    95.  
    96.         Vector3 MoveVector = new Vector3 (0, VertVelocity, 0);
    97.         PlayerController.Move (MoveVector * Time.deltaTime);
    98.     }
    99.      
    100. }
    101.  


    Camera Code:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ThirdPersonCAMScript : MonoBehaviour {
    5.  
    6.     private const float Y_ANGLE_MIN = 0.0f;
    7.     private const float Y_ANGLE_MAX = 30.0f;
    8.  
    9.     public Transform lookAt;
    10.     public Transform camTransform;
    11.  
    12.     private Camera cam;
    13.  
    14.     private float distance = 10.0f;
    15.     public float currentX = 0.0f;
    16.     public float currentY = 0.0f;
    17.     private float sensitivityX = 4.0f;
    18.     private float sensitivityY = 1.0f;
    19.  
    20.     // Use this for initialization
    21.     void Start () {
    22.         camTransform = transform;
    23.         cam = Camera.main;
    24.     }
    25.  
    26.     // Update is called once per frame
    27.     void Update () {
    28.         currentX += Input.GetAxis ("Mouse X");
    29.         currentY += Input.GetAxis ("Mouse Y");
    30.  
    31.         currentY = Mathf.Clamp (currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);
    32.  
    33.     }
    34.  
    35.     // Update is called once per frame
    36.     void LateUpdate () {
    37.         Vector3 dir = new Vector3 (0, 0, -distance);
    38.         Quaternion rotation = Quaternion.Euler (currentY, currentX, 0);
    39.         camTransform.position = lookAt.position + rotation * dir;
    40.         camTransform.LookAt(lookAt.position);
    41.  
    42.     }
    43.  
    44. }


    Thanks in advance for any help what so ever!
    ~Zak!
     
    Last edited: Sep 11, 2017
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Hi, and welcome to Unity :)
    First off, please take a moment to look at this page : https://forum.unity3d.com/threads/using-code-tags-properly.143875/
    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 :) (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. :)
     
  3. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    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.
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Ya, no problem. I love learning and trying stuff, too :)

    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 ;)
     
  5. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    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 ^^'
     
    Last edited: Sep 12, 2017
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Try this package I attached :)

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

    Attached Files:

  7. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    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<'
     
  8. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    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 :)
     
  9. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    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
     
  10. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    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.
     
  11. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    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.
     
  12. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    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??
     
  13. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    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.
     
  14. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Well, make sure you disable any other camera you might have ..

    The camera should be like this:
    -- Camera Rig
    -- Camera Pivot
    -- Actual Camera
     
  15. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    I have:
    LookAt: Capsule(Player)
    CamTransform: Main Camera
    CAMPivot: Main Camera
    CAM Rig: Main Camera.

    I only have the Main Camera.
     
  16. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Ok. 1 step back here. Did you open the package I sent? :)
     
  17. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    It has a camera rig prefab in it.
     
  18. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Yes. - And I see it, But wont let me open it, How do I use it?
     
  19. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    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?
     
  20. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    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
     
  21. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Please be specific so I am not confused, again lol

    "Unity won't let you get it into an object or anything" -- You mean the prefab??
     
  22. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Yeah, I can drag and drop it onto anything, Am I missing something or is there another method of using the prefab?
     
  23. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Just drag it into the scene in general.. like the scene view ;) (or the hierarchy would work also)
     
  24. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Sorry I cant. I mispelt the can, I cant drag and drop. It comes up with the circle icon with the line through it. Something Im doing wrong?
     
  25. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay, this is the blue camera rig in the project area?
    Are you sure you're not trying to drag it into the game window instead of the scene?
    Like I said, you could also drag it to the hierarchy..?
     
  26. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    This is the Camera Rig prefab that you have provided and it will not go into the hierarchy or the scene window. And I am not putting it into the gamewindow.

    Even tried it with a new project file and it doesnt allow me to add it still.

    EDIT: It doesnt have a blue icon it turns out. I wonder why that is. Let me try and again.
     
  27. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Sure.. Try again. it's possible you have a lower version of unity than I?
    I'm using : 2017.0.1p5
     
  28. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Since this conversation has a lot of back n forth :)

    If you have the scripts without a problem..
    It's so easy to recreate the camera:
    Just do this:
    create empty object
    create child empty object
    put the camera , as a child, on the child object.

    Then, put the cam script (yours that i modified) on the rig. and just reset the variables so they match the right spots/links.
     
  29. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Unity Version 5.3.5f1 - And nope, still doesnt work. Really odd.
     
  30. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    But you have the scripts okay, is that right?
     
  31. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Yeah, I do. I just gotta try and figure out how to do it correctly. Do you have a screenshot of how the set up looks? Just a point of reference as I dont quite understand what you mean like, I understand making a Gameobject then do I make another Gameobject, make the first one its parent than attach a camera object to its child so its like: FirstGameObject > SecondGameObject > Camera? Like that?
     
  32. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Yes, exactly like that. The first 2 are just "Empty game object" then the camera.

    Then, put the script on the top (parent) game object.

    Then, I'd say make the 2nd child position: 0,1.5,0
    And camera object position: 0,0,-5
    Just to test :) you can adjust a little bit for your liking.
     
  33. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Then the Camera Rig and Pivot is what then? Those Parenting objects?
     
  34. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Yes, parent = Cam rig
    Pivot = child of parent
    Cam = child of pivot
     
  35. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Well, I managed to get it all set up and it still has the bumping along the ground problem still. Did you do this for FPS or the Third person in mind just out of curiousity?
     
  36. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Well it should be third person, can you export a package with just the camera, 2 scripts + your character (or even a capsule)? post the package here on the forum.
    I dunno how yours is so different but if i look at it maybe i can see.
     
  37. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Yeah okay, here you go. See if you can do anything with it lol
     

    Attached Files:

  38. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I'm going to open it now..
     
  39. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Okay -- list of problems/fixes for you!

    Box (ground) doesn't need a mesh collider (i would delete that if I were you, keep the box collider).
    Player does not need a capsule collider (but I guess maybe you can keep it if you want it.. honestly I've never used the character controller outside of small tests - like helping you -- so I'm not sure 100% on that)

    Now I'm going to try to remember the camera mistakes you made:
    1) put the cam script on the top parent.
    2) the cam rig _is_ the top parent. So, on the character movement script, make sure you reference that (and not the 'actual camera'
    3) check your other script to make sure that's done right, also (just in case, because I forget)
    4) here are the settings for the camera rig, pivot and camera positions!

    Camera Rig (top parent): position = (actually doesn't matter, anything)
    Camera Pivot (Cam Parent 2, as you called it): position : x = 0, y = 1.5, z = 0
    Camera: position: x = 0, y = 0, z = -5

    After that let me know how it goes! lol :)
     
  40. TheDevilsHitman

    TheDevilsHitman

    Joined:
    Sep 11, 2017
    Posts:
    19
    Thanks! It works entirely now exactly what I wanted! Thanks alot!
     
  41. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Hey cool glad ya got it working :)