Ultra-detailed, how does unity make a joystick for a character to walk?

introduce

In games, the movement joystick is a common user interface element that allows players to control the movement of game objects through touch or mouse input. A mobile joystick usually consists of a circular or square background and a small ball (called a thumbstick) that you can drag. The player can control the movement direction and speed of the game object by dragging the thumbstick.

insert image description here

insert image description here

insert image description here


method

1. Create the first canvas image to display the joystick area

insert image description here


2. Create a second canvas image to display the control points of the joystick

insert image description here
insert image description here


3. Mount the script GameTouch to the second picture, and set the Tag to "Player"

The following are comments for each line of code in the GameTouch script:

using UnityEngine;
using UnityEngine.EventSystems;  // 引入Unity事件系统命名空间

public class GameTouch : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    
    
	Vector2 startPos;  // 记录遥杆起始位置
	public Vector2 Pos;  // 记录遥杆的移动值

	public void OnBeginDrag(PointerEventData eventData)  // 当玩家开始拖拽遥杆时执行
	{
    
    
		startPos = transform.position;  // 记录遥杆的起始位置
	}

	public void OnDrag(PointerEventData eventData)  // 当玩家拖拽遥杆时执行
	{
    
    
		Pos = eventData.position - startPos;  // 计算遥杆的移动值
		transform.position = Vector2.ClampMagnitude(Pos, 30) + startPos;  // 移动遥杆并限制其最大移动距离
	}

	public void OnEndDrag(PointerEventData eventData)  // 当玩家停止拖拽遥杆时执行
	{
    
    
		Pos = Vector2.zero;  // 重置遥杆的移动值
		transform.position = startPos;  // 将遥杆移回起始位置
	}
}

This script implements a basic mobile joystick. When the player drags the joystick, it will record the movement value of the joystick and move the joystick to the appropriate position. This script implements three interfaces: IBeginDragHandler, IDragHandler, and IEndDragHandler, which are interfaces in the Unity event system for handling user input events. When the player starts to drag the joystick, the OnBeginDrag() function will record the starting position of the joystick; when the player drags the joystick, the OnDrag() function will calculate the movement value of the joystick and move the joystick to the appropriate position. position, and limit its maximum moving distance; when the player stops dragging the joystick, the OnEndDrag() function will reset the movement value of the joystick and move the joystick back to the starting position.

insert image description here


4. Create a new cube as the control object of the joystick, and mount the script ObjectMover

using UnityEngine;

public class ObjectMover : MonoBehaviour
{
    
    
	public float speed = 5f; // 物体移动的速度
	private GameTouch gameTouch; // 存储GameTouch组件的引用

	private void Start()
	{
    
    
		GameObject player = GameObject.FindGameObjectWithTag("Player"); // 获取标签为"Player"的物体
		if (player != null) {
    
    
			gameTouch = player.GetComponent<GameTouch>(); // 获取GameTouch组件
		}
		if (gameTouch == null) {
    
    
			Debug.LogError("GameTouch component not found on Player object!");
		}
	}

	private void Update()
	{
    
    
		// 获取遥杆的移动值
		float horizontal = gameTouch.Pos.x;
		float vertical = gameTouch.Pos.y;

		// 计算物体的移动方向
		Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

		// 计算物体的移动距离
		float distance = Mathf.Clamp(gameTouch.Pos.magnitude, 0f, 30f) / 30f;
		distance *= speed * Time.deltaTime;

		// 移动物体
		transform.position += direction * distance;
	}
}

insert image description here
A class named ObjectMover is defined, which inherits from MonoBehaviour, indicating that it is a Unity component.

A public floating-point variable speed is declared to control the moving speed of the object.

A private GameTouch type variable gameTouch is declared to store the reference of the GameTouch component.

The Start() method is called when the script starts. In this method, a game object named "Player" is found through the label, and a reference to the GameTouch component on it is obtained.

If the GameTouch component is found, assign it to the gameTouch variable; otherwise, output an error message.

The Update() method is called every frame. In this method, get the Pos property of gameTouch, which stores the movement value of a joystick.

Calculate the moving direction of the object according to the moving value of the joystick, and use the normalized method of Vector3 to standardize it.

Calculate the moving distance of the object, use the Mathf.Clamp method to limit the moving value between 0 and 30, and multiply it by speed and Time.deltaTime to ensure smooth movement.

Move the object along the moving direction multiplied by the moving distance, and update the position of the object.


5. Adjust the camera position for easy observation

insert image description here


demo

insert image description here


Guess you like

Origin blog.csdn.net/qq_20179331/article/details/130702986