• 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
Question by loxagos_snake · Jun 17, 2015 at 01:29 AM · movementinputdirectioncrosshair

Determining movement direction through crosshair

Hello fellow developers. So, the last week I've been fighting to get a camera that faces the same direction as the character to work. My solution was to use a plane, slap a crosshair texture on it, dub that as a 'Follower' object in the Hierarchy which the camera always faces, and stick the camera a certain distance from the player. I'm focusing on the main controls of the game, so my next concern is movement. Since I haven't worked on any animations yet, it's all transformations. I can make the character rotate correctly, strafe and walk forward, but there is one problem: the character (and that is to be expected) doesn't move in the local forward direction (that is, towards the crosshair) but along the global Z axis. What I want to achieve is, when the player presses the Forward button, the character moves towards the crosshair as in most modern TPS shooters. I'll give you my code below.

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour {
 
     /* This script controls all aspects of player behavior. It includes moveDirectional, shooting and various other interactions */
 
     public float playerSpeed = 4f; // Player's moveDirectional speed
     public float jumpSpeed = 400f; // Player's jump speed
     public float jumpMaxDistance = 0.5f; // Public for debugging purposes
     public float sensitivity = 1f;
     public float rotSmooth = 1f;
 
     private Vector3 playerPos; 
     
     Vector3 newMouseMove;
     Vector3 moveDirectional; // Motion vector
     Vector3 moveMouse;
     Rigidbody player_rb; // Reference to the player's rigidbody
     Transform player_trans; // Reference to the player's transform
     GameObject follower; // Reference to the follower crosshair
     
 
 
 
     void Awake()
     {
     /* ----- SETUP ----- */
         follower = GameObject.FindGameObjectWithTag("Follower");
 
         player_rb = GetComponent<Rigidbody>(); 
         player_trans = GetComponent<Transform>();
     }
 
 
     void Update()
     {
         /* DEBUGGING */
         Debug.DrawLine(player_trans.position, new Vector3(0f,0f,0f));
     }
 
 
     void FixedUpdate () 
     {
 
 
         /* ----- BASIC XY PLANE moveDirectional ----- */
 
         float hMove = Input.GetAxisRaw ("Horizontal");
         float vMove = Input.GetAxisRaw ("Vertical");
 
         if (hMove != 0 || vMove != 0)
         {
 
         
         }
 
         /* ----- JUMPING ----- */
 
         if ( (RayLanded() && Input.GetKey("space")) )
             player_rb.velocity = Vector3.up * jumpSpeed * Time.deltaTime;
 
         /* ----- MOUSE AIM ----- */
 
         // Lock and hide the cursor
         Cursor.lockState = CursorLockMode.Locked;
         Cursor.visible = false;
 
         float hMouse = Input.GetAxisRaw ("Mouse X");
         float vMouse = Input.GetAxisRaw ("Mouse Y");
 
         float hRotation = hMouse * sensitivity * Time.deltaTime; 
         // float vRotation = vMouse * sensitivity * Time.deltaTime; 
 
         transform.Rotate(0f,hRotation,0f);
 
 
     }
 
 
 
     /* ----- Other functions ----- */
 
     // Checks if the player is grounded
       bool RayLanded()
     {
         Ray jumpDetect = new Ray(player_trans.position,Vector3.down);

         RaycastHit hitGround;
         
         if (Physics.Raycast (jumpDetect, out hitGround, jumpMaxDistance))
         {
             return true;
             
         }
         return false;
     }
 
     // Checks if the player has pressed the Use key
     public bool isInteracting()
     {
         if (Input.GetKey ("e"))
             return true;
         else
             return false;
     }
 
 
 }


I guess it's not a code gem, but bear with me, I'm just starting out. Also, ignore some of the other functions, it's all pretty experimental. Also, I know there is a character controller, but I'd like to build the controller myself as it helps me understand what I'm doing better.

I've thought of many different solutions: transforming from local to global coordinates, defining my own 'forward vector' and detect direction through angles, but I can't think it through. Any suggestions are welcome. Thank you for your time!

Comment

People who like this

0 Show 0
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

2 Replies

  • Sort: 
avatar image
Best Answer

Answer by smallbit · Jun 17, 2015 at 02:53 AM

Moving player forward is as simple as moving it along its forward vector, which is modified upon rotation (i.e. like here http://docs.unity3d.com/ScriptReference/Transform.Translate.html) I cannot fix your code because you did not provide any for the movement. Also you will find many opinions here, saying that the way you did the jump by changing rigidbody velocity directly is not a very good idea. You should add force instead and let the velocity calculate by unity.

Also idea of writing your own controller instead of using ready one is very good, and has many benefits which you will find later on upon developing.

Comment
loxagos_snake

People who like this

1 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 loxagos_snake · Jun 17, 2015 at 09:16 AM 0
Share

Thank you! That is EXACTLY what I was looking for, movement relative to the already-rotated local player Z axis. My problem is solved.

avatar image

Answer by robbagus · Jun 17, 2015 at 06:32 AM

Using a plane for cross-hair is unnecessary (unless you need it for something else which I don't know), I'd recommend using OnGUI to draw the cross-hair as Texture2D on a GUI layer, and place it right in the middle of screen.width and screen.height. Look into this for GUI.DrawTexture; http://docs.unity3d.com/ScriptReference/GUI.DrawTexture.html

To get the camera to look at where your character is looking you simply attach the camera under your character as a child in your hierarchy. Then your camera rotation will be dependant on your character. Of course you have to do the alignment yourself. First you'll want to place your character and camera in the same location and make sure that they're facing the same direction, then you attach the camera as child of your character and you're done. Since you're making a TPS, simply move the camera back. Also don't forget you may need a MouseLook script (or if you have something similiar) so your character can look around. However there's a down side to this as the movement of the camera will be very rigid, you'll want to google for position lerping so your camera can have a nice smooth transition. But of course it's not a must, just a nice touch. For lerping, check this out; http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

To get your character movement right you have to accommodate your movement with your character's local rotation. I've never done that maths myself but there are more than enough tutorial out there showing and explaining how to do that. Check out GhostFreeRoamCamera, it's a free asset and what you're looking for (camera moving forward where ever it's currently looking at). https://www.assetstore.unity3d.com/en/#!/content/19250

Comment
loxagos_snake

People who like this

1 Show 0 · 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

Unity Answers is in Read-Only mode

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta on June 13. Please note, Unity Answers is now in read-only so we can prepare for the final data migration.

For more information and updates, please read our full announcement thread in the Unity Forum.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Horizontal/Vertical input immediately zero after key release 1 Answer

New Input System with Vector2 in only four directions 0 Answers

How do I turn 1 objects rotation into another objects movement direction? 1 Answer

set position in direction 0 Answers

Why isn't this working? 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