K
K
Koton222022-01-18 23:11:34
Unity
Koton22, 2022-01-18 23:11:34

How to make character rotation with Joystick Unity 3D?

There is a script for moving the player using the Fixed Joystick.
Playing on Unity 3D
( https://assetstore.unity.com/packages/tools/input-... )
1. How to make the player move constantly?
2. How to rotate the character using the joystick?

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

[RequireComponent(typeof(Rigidbody), typeof (BoxCollider))]
public class PlayerController : MonoBehaviour
{
    [SerializeField] public float runSpeed;
    [SerializeField] private Rigidbody _rigidbody;
    [SerializeField] private FixedJoystick _joystick;
    [SerializeField] private float _moveSpeed;

    private void FixedUpdate()
    {
        _rigidbody.velocity = new Vector3(_joystick.Horizontal * _moveSpeed, _rigidbody.velocity.y, _joystick.Vertical * _moveSpeed);
        if (_joystick.Horizontal != 0 || _joystick.Vertical != 0)
        {
            transform.rotation = Quaternion.LookRotation(_rigidbody.velocity);
        }
        _rigidbody.AddForce(0,0,runSpeed*Time.deltaTime);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2022-01-18
@Koton22

1. Instead of AddForce, simply set the speed of movement (via RigidBody.velocity) - here you have constant movement at a constant speed
2. The joystick returns the value of its two axes from -1 to 1 - using them, using school formulas, you can calculate the angle of rotation (google: how to convert cartesian coordinates to polar coordinates).
But in theory, you can just normalize this vector, multiply it scalarly by the speed, and transfer it immediately to velocity and LookAt, without unnecessary calculations
.
Or vice versa - an extra velocity, because the Unity documentation recommends using only one.
I also don't see where the _moveSpeed ​​value is set (and how it differs from runSpeed).
If nowhere, it will always be 0, and the character will not move.
In general, carefully read the documentation and your own code, and try to understand how the engine should perceive it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question