How do I rotate an object around its axis?/Unity3d

There is a ball that I want to rotate around its axis forward .

enter a description of the image here

The question itself would be very easy, if not for one but.

Object movement:

rb.MovePosition(transform.position + (transform.forward * Time.deltaTime *speed));

In order to change the direction of the character, I rotate it, i.e. I need to use forward so that the character can not just go forward on the X axis, but also change directions and move forward on it.But as you can see if I just start rotating it like this transform.Rotate(Vector3.right *3), then forward will not work correctly.

Object rotation :

     private Touch touch1;
    
        private Vector2 TouchPosition;
    
        private Quaternion rotationY;
    
        private float rotateSpeedModifier = 0.7f;

        void Update()
{
            if (Input.touchCount > 0)
                    {
                        touch1 = Input.GetTouch(0);
                        if (touch1.phase == TouchPhase.Moved)
                        {
                            rotationY = Quaternion.Euler(
                                0f,
                                touch1.deltaPosition.x * rotateSpeedModifier,
                                0f);
                            transform.rotation = rotationY * transform.rotation;
                        }
                    }
    }

The only way out I see is to change the mechanics of movement, but how?

//Rotating the animation is probably a bad idea.

Author: Дух сообщества, 2019-10-29

1 answers

The optimal way would be to use physical movement, rather than rotate + move forward.

using UnityEngine;

//эта строчка гарантирует что наш скрипт не завалится 
//ести на плеере будет отсутствовать компонент Rigidbody
[RequireComponent(typeof(Rigidbody))]
public class Movement : MonoBehaviour
{
    public float Speed = 10f;
    public float JumpForce = 300f;

    //что бы эта переменная работала добавьте тэг "Ground" на вашу поверхность земли
    private bool _isGrounded;
    private Rigidbody _rb;

    void Start()
    {
        _rb = GetComponent<Rigidbody>();
    }

    // обратите внимание что все действия с физикой 
    // необходимо обрабатывать в FixedUpdate, а не в Update
    void FixedUpdate()
    {
        MovementLogic();
        JumpLogic();
    }

    private void MovementLogic()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");

        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        _rb.AddForce(movement * Speed);
    }

    private void JumpLogic()
    {
        if (Input.GetAxis("Jump") > 0)
        {
            if (_isGrounded)
            {
                _rb.AddForce(Vector3.up * JumpForce);

                // Обратите внимание что я делаю на основе Vector3.up 
                // а не на основе transform.up. Если персонаж упал или 
                // если персонаж -- шар, то его личный "верх" может 
                // любое направление. Влево, вправо, вниз...
                // Но нам нужен скачек только в абсолютный вверх, 
                // потому и Vector3.up
            }
        }
    }

    void OnCollisionEnter(Collision collision)
    {
        IsGroundedUpate(collision, true);
    }

    void OnCollisionExit(Collision collision)
    {
        IsGroundedUpate(collision, false);
    }

    private void IsGroundedUpate(Collision collision, bool value)
    {
        if (collision.gameObject.tag == ("Ground"))
        {
            _isGrounded = value;
        }
    }
}

The code is taken from the topic: Correct implementation of character movement

And there it is taken from the unity documentation and finalized.

In your case, you need to cut out the logic of the jump, as well as lock the object in height (y) when touching the "ground", as far as I understand.


But if you really answer the question itself: how to rotate the ball around its axis...

To do this, just use Rotate. But the most important thing to consider is that the pivot point would be in the center of the object. Because the object will rotate around it.

 1
Author: Andrew, 2019-10-29 15:53:24