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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Want to rotate cube

Discussion in 'Scripting' started by iMihai9, Jun 12, 2018.

  1. iMihai9

    iMihai9

    Joined:
    Jun 4, 2018
    Posts:
    11
    I have that code :
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Movement : MonoBehaviour {
    6.  
    7.     public float speed = 10f;
    8.     public float mapWidth = 5f;
    9.  
    10.     private Rigidbody rb;
    11.  
    12.     void Start()
    13.     {
    14.         rb = GetComponent<Rigidbody>();
    15.     }
    16.  
    17.     void FixedUpdate()
    18.     {
    19.         float x = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
    20.  
    21.         transform.Rotate(Vector3.up, -Input.GetAxis("Horizontal") * speed * Time.deltaTime);
    22.  
    23.         Vector3 newPosition = rb.position + Vector3.right * x;
    24.  
    25.         newPosition.x = Mathf.Clamp(newPosition.x, -mapWidth, mapWidth);
    26.  
    27.         rb.MovePosition(newPosition);
    28.  
    29.     }
    30. }
    31.  
    and my cube sliding left and right , but don't rotate in left or right
    Can someone help me please?
     
  2. bakir-omarov

    bakir-omarov

    Joined:
    Aug 1, 2015
    Posts:
    48
    Just delete "speed" from this the line 19. And you can increase speed two times.

    Your code must be like:
    Code (CSharp):
    1.  
    2.    void FixedUpdate()
    3.     {
    4.         float x = Input.GetAxis("Horizontal") * Time.deltaTime;
    5.         transform.Rotate(Vector3.up, -Input.GetAxis("Horizontal") * speed);
    6.         Vector3 newPosition = rb.position + Vector3.right * x;
    7.         newPosition.x = Mathf.Clamp(newPosition.x, -mapWidth, mapWidth);
    8.         rb.MovePosition(newPosition);
    9.     }
    10.  
     
    Last edited: Jun 12, 2018
  3. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    he is not using x in the rotation, on in the position.

    Isn't the issue that he is using horizontal to control both position and rotation
     
  4. bakir-omarov

    bakir-omarov

    Joined:
    Aug 1, 2015
    Posts:
    48
    Yeap, he is not using, but it is Unity Physics. Moving and Rotating both affecting each other (because of Rigidbody). I checked both (his and mine code) on cube object, and saw the effect. So that is why i advised to change
     
    johne5 likes this.