Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by rogmidd · Oct 10, 2014 at 12:58 PM · c#movementfirst person controller

How to moved a fixed amount per key press using first person character controller

I'm trying to write a simple 1st person character controller that stays on a grid (ie. turning 90 degrees per side keystroke, and moving 2 metres per forward/back keystroke. I've come up with the code below, in an attempt to cap each move to 2m. When i use Time.deltaTime, the distance moved fluctuates inconsistently around 2m. When i use Time.fixedDeltaTime, the distance moved is consistent, but is over 2 metres.

 using UnityEngine;
 using System.Collections;
 
 [RequireComponent (typeof(CharacterController))]
 
 public class FPCSteps : MonoBehaviour {
 
     float temp;
     bool isRotating;
     int horizontalDirection;
 
     float temp2;
     bool isMoving;
     int forwardDirection;
 
     CharacterController characterController;
 
     
     // Use this for initialization
     void Start () {
         Screen.lockCursor = true;
         characterController = GetComponent<CharacterController> ();
             
     }
     
     // Update is called once per frame
     void Update () {
 
         if (Input.GetKeyDown (KeyCode.W) && !isMoving) {
             isMoving = true;
             forwardDirection = 1;
             temp2 = 0;
         }
 
         if (Input.GetKeyDown (KeyCode.S) && !isMoving) {
             isMoving = true;
             forwardDirection = -1;
             temp2 = 0;
             
         }
 
         if (Input.GetKeyDown (KeyCode.D) && !isRotating) {
             isRotating = true;
             horizontalDirection = 1;
             temp = 0;
         }
         if (Input.GetKeyDown (KeyCode.A) && !isRotating) {
             isRotating = true;
             horizontalDirection = -1;
             temp = 0;
         }
 
         transform.Rotate (Vector3.up * 90 * Time.fixedDeltaTime * horizontalDirection, Space.World);
         temp += 90 * Time.fixedDeltaTime;
         if (temp >= 90) {
             temp = 0;
             horizontalDirection = 0;
             isRotating = false;
         }
 
         Camera cam = Camera.main;
         characterController.Move (cam.transform.forward * forwardDirection * 2 * Time.deltaTime);
         temp2 += 2 * Time.deltaTime;
         if (temp2 >= 2){
             temp2 = 0;
             forwardDirection = 0;
             isMoving = false;
         }
 
     }
     
 }

  

Sorry if there's something obvious i've missed, i'm still very new and clueless about C#. If anyone can help, or point me towards a resource that might help, it would be greatly appreciated!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by robertbu · Oct 10, 2014 at 04:20 PM

There is no issue here related to C#, but there is an issue here to your approach. Your grid movement is trying to place your character at a precise place, but your code is using relative movements. First it is using the relative direction of 'cam.transform.forward'. Second, each move is relative to the last. And finally you are using Time.deltaTime where the time from frame to frame will change. With floating point imprecision added in, even if you could working out the current issues with your code, over time a error will creep in. If it were me, I'd make the following changes.

  • While not strictly necessary, I'd change the grid to 1 x 1 rather than 2 x 2. This might mean changing the distance or the FOV of the camera and/or resizing elements, but it just makes debugging and rounding easier.

  • When moving calculate an absolute position. Note I'm confused about the use of 'cam.transform.forward'. Using this value only makes sense if the camera will be rotating. Use absolute directions or values instead. For example, if you press the 'A' key, you will subtract 1.0 from the 'x' value of the current position to generate the new goal position. Or alternately you can add Vector3.left to your current position to get the goal.

  • Round the new goal position: 'goalPos.x = Mathf.Round(goalPos.x);' This will eliminate errors creeping in over time.

  • For each move, first calculate the move. Then test the distance against the remaining distance. If the remain distance is shorter, use that instead:


    Vector3 dir = goalPos - transform.position; Vector3 move = dir.normalized Time.deltaTime speed; if (move.magnitude > dir.magnitude) { characterController.Move (dir); isMoving = false; } else { characterController.Move(move); }

'speed' will be a variable you define and will represent units of movement per second.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rogmidd · Oct 13, 2014 at 07:26 AM 0
Share

Thanks for your help! And thank you for explaining the reasoning behind it. This was exactly what i needed.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

2 People are following this question.

avatar image avatar image

Related Questions

Making a bubble level (not a game but work tool) 1 Answer

Problem with player movements 1 Answer

Character Rotation 2 Answers

Jump and move (CharacterController.velocity) C# 0 Answers

C# Twitchy Camera Movement 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges