Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Want to make my player rotate - C#

Discussion in 'Scripting' started by airesdav, Feb 11, 2013.

  1. airesdav

    airesdav

    Joined:
    Nov 13, 2012
    Posts:
    128
    I am fairly new to C# and i was wondering how i make my player rotate left and right i defined the rotatespeed at the top

    Code (csharp):
    1.  
    2. public float RotateSpeed = 3.0f;
    3.  

    How do i make it rotate i know it goes in the update function, i tried the code in the script from the Unity script ref but does not work
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class example : MonoBehaviour {
    6.     void Update() {
    7.         transform.Rotate(Vector3.right * Time.deltaTime);
    8.     }
    9. }
    10.  


    here is my code does anyone have an example that they can show me i am okay with the Javascipt example

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. // Place the script in the Camera-Control group in the component menu
    6. [AddComponentMenu("Camera-Control/Smooth Follow CSharp")]
    7.  
    8. public class SmoothFollowCSharp : MonoBehaviour
    9. {
    10.     /*
    11.     This camera smoothes out rotation around the y-axis and height.
    12.     Horizontal Distance to the target is always fixed.
    13.  
    14.     There are many different ways to smooth the rotation but doing it this way gives you a lot of control over how the camera behaves.
    15.  
    16.     For every of those smoothed values we calculate the wanted value and the current value.
    17.     Then we smooth it using the Lerp function.
    18.     Then we apply the smoothed values to the transform's position.
    19.     */
    20.  
    21.     // The target we are following
    22.     public Transform target;
    23.     // The distance in the x-z plane to the target
    24.     public float distance = 10.0f;
    25.     // the height we want the camera to be above the target
    26.     public float height = 5.0f;
    27.     // How much we
    28.     public float heightDamping = 2.0f;
    29.     public float rotationDamping = 3.0f;
    30.    
    31.     public float RotateSpeed = 3.0f;
    32.  
    33.     void  LateUpdate ()
    34.     {
    35.        // Early out if we don't have a target
    36.        if (!target)
    37.          return;
    38.  
    39.        // Calculate the current rotation angles
    40.        float wantedRotationAngle = target.eulerAngles.y;
    41.        float wantedHeight = target.position.y + height;
    42.        float currentRotationAngle = transform.eulerAngles.y;
    43.        float currentHeight = transform.position.y;
    44.        
    45.    
    46.  
    47.        // Damp the rotation around the y-axis
    48.        currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
    49.  
    50.        // Damp the height
    51.        currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
    52.  
    53.        // Convert the angle into a rotation
    54.        Quaternion currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
    55.  
    56.        // Set the position of the camera on the x-z plane to:
    57.        // distance meters behind the target
    58.        transform.position = target.position;
    59.        transform.position -= currentRotation * Vector3.forward * distance;
    60.        
    61.        
    62.  
    63.        // Set the height of the camera
    64.        transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
    65.  
    66.        // Always look at the target
    67.        transform.LookAt (target);
    68.     }
    69. }
    70.  
    71.  
    72.  
    ;-)
     
    Ridgebody2D likes this.
  2. SkaredCreations

    SkaredCreations

    Joined:
    Sep 29, 2010
    Posts:
    296
    This code rotates smoothly the object left/right by holding left/right keyboard arrows:
    Code (csharp):
    1.  
    2. public class Test : MonoBehaviour {
    3.    
    4.     public float RotateSpeed = 30f;
    5.    
    6.     void Update () {
    7.         if (Input.GetKey(KeyCode.LeftArrow))
    8.             transform.Rotate(-Vector3.up * RotateSpeed * Time.deltaTime);
    9.         else if (Input.GetKey(KeyCode.RightArrow))
    10.             transform.Rotate(Vector3.up * RotateSpeed * Time.deltaTime);
    11.     }
    12. }
    13.  
     
    Disgrabled, Worador, CaioYon and 2 others like this.
  3. Ping1024

    Ping1024

    Joined:
    Jan 4, 2020
    Posts:
    1
    you have to change the
    Code (csharp):
    1. -Vector3.up
    to
    Code (csharp):
    1. Vector3.forward
    , and
    Code (csharp):
    1. Vector3.up
    to
    Code (csharp):
    1. -Vector3.forward
    in the newer versions of Unity.
     
  4. unturnedfoxy

    unturnedfoxy

    Joined:
    May 18, 2020
    Posts:
    1
    It gives me two errors when I enter this script. Someone please help?
     
    Cazoy likes this.
  5. BrainwavesToBinary

    BrainwavesToBinary

    Joined:
    Jul 8, 2019
    Posts:
    26
    Hi, this is an old thread, and even with Sheepsee's update from this past January, there's a better way to handle this. You likely got here via search engine, as I did while actually looking for something else:-/ In any case:

    Firstly, I see that you're new here - it helps if you paste your code when you have an issue, and communicate the specific error text as well. Even if you copy/paste someone else's script, sometimes something gets mis-pasted or altered in some way that no one else can help with if they can't see it. You can use the "insert code" option at the top of the reply box to format it easily.

    Secondly, even without using Unity's new input system, which I still haven't gotten around to learning, you can use "GetAxis" instead of "GetKey" when you are setting up movement controls. This will allow you simplify your code by removing the if/else if logic in the solution above. Your code could look more like this (I added comments to explain things a little more):

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerMovement : MonoBehaviour
    4. {
    5.     /*
    6.      * Use [SerializeField] instead of public declaration for the ability to modify in the Inspector
    7.      * unless other scripts will need direct access to 'turnSpeed'
    8.      */
    9.     [SerializeField] float turnSpeed = 20f;
    10.  
    11.  
    12.  
    13.     void Update()
    14.     {
    15.         /*
    16.          * GetAxis returns a value between -1 and 1 (and not zero) when a left or right arrow key (or 'A' or 'D')
    17.          * is pressed.  For simplicity and readability, I'm storing that value in a variable called 'horizontalInput'
    18.          */
    19.         float horizontalInput = Input.GetAxis("Horizontal");
    20.  
    21.         /*
    22.          * Here we use 'Vector3.up' since using it here is equivalent to rotating around the y axis (0, 1, 0).
    23.          * Also, because 'horizontalInput' can be negative when the 'left' arrow or 'A' is pressed, it will
    24.          * make the Y rotation negative, thus rotating the player to the left.  A positive value rotates to the
    25.          * right.
    26.          */
    27.         transform.Rotate(Vector3.up * horizontalInput * turnSpeed * Time.deltaTime);
    28.     }
    29. }
     
  6. thorns111

    thorns111

    Joined:
    Feb 22, 2019
    Posts:
    5
    hi im having simular troubble with my code
    i any trying to rotate the player when the (A or D) key is held down. i need it to chhange the players direction.
    i tried using

    1. transform.Rotate(Vector3.up * horizontalInput * turnSpeed * Time.deltaTime);
    and the player still does not rotate

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

    public class movementcb : MonoBehaviour
    {
    public float rotateSpeed = 30f;
    private float speed = 0.5f;
    void FixedUpdate()
    {


    }

    // Start is called before the first frame update
    void Start()
    {
    Debug.Log("u can start now");

    }

    // Update is called once per frame
    void Update()
    {
    Debug.Log("movement update");

    Vector3 position = this.transform.position;
    if (Input.GetKey(KeyCode.W))
    //forward


    {
    Debug.Log("walk forward");
    position.z += position.z * speed * Time.deltaTime;
    this.transform.position = position;

    }
    else if (Input.GetKey(KeyCode.S)) //backwards
    {
    position.z -= position.z * speed * Time.deltaTime;
    this.transform.position = position;
    Debug.Log("walk backwards");


    }

    else if (Input.GetKey(KeyCode.A))
    //left
    {
    position.x -= position.x * speed * Time.deltaTime;
    this.transform.position = position;
    Debug.Log("turn left");


    }

    else if (Input.GetKey(KeyCode.D))
    //right
    {
    position.x += position.x * speed * Time.deltaTime;
    this.transform.position = position;
    Debug.Log("turn right");
    }
    //----------------Jumping----------------
    else if (Input.GetKey(KeyCode.Space))
    //up
    {
    position.y++;
    this.transform.position = position;
    }
    else if (Input.GetKey(KeyCode.Z))
    //up
    {
    position.y--;
    this.transform.position = position;
    }


    }
    }
     
  7. BrainwavesToBinary

    BrainwavesToBinary

    Joined:
    Jul 8, 2019
    Posts:
    26
    Hi @lectriss ,

    I see you just joined - welcome to the forum! Let's start with the problems with your methodology:

    I hadn't seen your method of getting something to move before, so I just copied it and attached it to an object in Unity - not only did the object not turn/rotate, it didn't move forward or backward. Oddly enough, it did jump (obviously, with the addition of a Rigidbody component to the Player object). The way you were trying to make it move looks like what 'transform.Translate()' is designed to accomplish, so I've used that in my code below. For consistency, I used basically the same method for jumping. You could alternatively use the physics engine to apply force to your player's Rigidbody to move forward, rotate, and jump with some changes to the code.

    Also, with your method, you are using 'else if' to test for input which means that each of those conditions is tested to the exclusion of others in that 'if' thread. This means that with your method, you can't have the player moving forward while turning or jumping. To get around that, I use multiple, independent 'if' statements that can be tested in addition to each other, allowing you to move forward/backward while turning and/or jumping.

    Code, with comments, is below. FYI, in the future when you want to paste code into your post, you can use the 'Insert Code' option in the post/reply menu.

    Code (CSharp):
    1. public class PlayerMover : MonoBehaviour
    2. {
    3.     // Using 'SerializeField' to keep these private but accessible for change in the Inspector
    4.     [SerializeField] private float rotateSpeed = 30f;
    5.     [SerializeField] private float speed = 0.5f;
    6.     [SerializeField] private float jumpPower = 50f;
    7.  
    8.     void Update()
    9.     {
    10.         // declare movement floats and associate them to the standard input system.  The
    11.         // 'Input.GetAxis()' returns a value between -1 and 1 (but not zero) when the key/button
    12.         // associated with it is pressed.  You can find these key/button assignments in:
    13.         // Edit -> Project Settings -> Input Manager
    14.         float verticalInput = Input.GetAxis("Vertical");
    15.         float horizontalInput = Input.GetAxis("Horizontal");
    16.         float jumpInput = Input.GetAxis("Jump");
    17.  
    18.         // Using a keyboard, the input values decalred above will rapidly hit 1 ('A') or -1 ('S').
    19.         if (verticalInput != 0)
    20.         {
    21.             // Vector3.forward = 1
    22.             // verticalInput = 1 or -1 depending on whether you are pressing 'W' or 'S'
    23.             // speed = 0.5f
    24.             // Time.deltaTime normalizes to latest framerate
    25.             transform.Translate(Vector3.forward * verticalInput * speed * Time.deltaTime);
    26.         }
    27.  
    28.         // basically the same explanation as above except that rather than 'Translate()', we
    29.         // use 'Rotate()'
    30.         if (horizontalInput != 0)
    31.         {
    32.             transform.Rotate(Vector3.up * horizontalInput * rotateSpeed * Time.deltaTime);
    33.         }
    34.  
    35.         // Similar execution as with moving forward/backward, except using 'Vector3.up'
    36.         if (jumpInput != 0)
    37.         {
    38.             transform.Translate(Vector3.up * jumpInput * jumpPower * Time.deltaTime);
    39.         }
    40.     }
    41. }
     
    Aman52 likes this.
  8. hUwUtao

    hUwUtao

    Joined:
    Jul 6, 2020
    Posts:
    1
    so, your ideal is using axis. but, i cant applied it to the real axis (sad)
     
  9. yox3

    yox3

    Joined:
    Nov 18, 2020
    Posts:
    8
    Hello...
    Same problem...
    I'm new to unity


    The error is:
    NullReferenceException: Object reference not set to an instance of an object
    PhotonTutorial.PlayerSpawner.Start () (at Assets/Scripts/PlayerSpawner.cs:16)

    Here's my code:

    Code (CSharp):
    1.  
    2. using Cinemachine;
    3. using Photon.Pun;
    4. using UnityEngine;
    5. using UnityEngine.SceneManagement;
    6. namespace PhotonTutorial
    7. {
    8.     public class PlayerSpawner : MonoBehaviourPun
    9.     {
    10.         [SerializeField] private GameObject PlayerPrefab = null;
    11.         [SerializeField] private CinemachineFreeLook playerCamera = null;
    12.         private void Start()
    13.         {
    14.             Scene scene = SceneManager.GetActiveScene();
    15.             if (scene.name == "Scene_Main")
    16.             {
    17.                 Cursor.lockState = CursorLockMode.Locked;
    18.             }
    19.             var player = PhotonNetwork.Instantiate(PlayerPrefab.name, Vector3.zero, Quaternion.identity);
    20.             playerCamera.Follow = player.transform;
    21.             playerCamera.LookAt = player.transform;
    22.         }
    23.    
    24.     }
    25. }
     
  10. yox3

    yox3

    Joined:
    Nov 18, 2020
    Posts:
    8
    Please help

    this is driving me CRAAAZY
     
  11. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    Please do not respond to EIGHT year old threads with irrelevant unrelated questions.

    For one, it's against forum rules.

    For two, start your own post, it's FREE!

    Furthermore, a nullref does NOT require a post, because...

    The answer is always the same... ALWAYS. It is the single most common error ever.

    Don't waste your life spinning around and round on this error. Instead, learn how to fix it fast... it's EASY!!

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception
    - also known as: Object reference not set to an instance of an object

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.
     
  12. yox3

    yox3

    Joined:
    Nov 18, 2020
    Posts:
    8

    Thank you my man!