unity 中物体围绕主角旋转(2d游戏)

挂载在要旋转的物体上

复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AutoRotationToPlayer : MonoBehaviour
{
    public Transform player;  // 玩家角色的Transform组件
    public float rotationSpeed = 50.0f;  // 火球围绕玩家旋转的速度
    public float radius = 1.0f;  // 火球距离玩家的初始半径

    private float angle = 0f;

    void Start()
    {
        int numberOfFireballs = transform.parent.childCount;
        int myIndex = transform.GetSiblingIndex();

        Vector3 newPosition = CalculateCirclePosition(player.position, radius, numberOfFireballs, myIndex);
        transform.position = newPosition; // 设置小球的初始位置
    }


    void Update()
    {
        RotationToPayer();
    }
    //围绕玩家旋转
    void RotationToPayer()
    {
        angle += rotationSpeed * Time.deltaTime;
        float angleInRadians = angle * Mathf.Deg2Rad;
        float x = player.position.x + radius * Mathf.Cos(angleInRadians);
        float y = player.position.y + radius * Mathf.Sin(angleInRadians);
        transform.position = new Vector3(x, y, transform.position.z);
    }
    //更新范围
    public void UpdateRange(float range)
    {
        radius = range;
        int numberOfFireballs = transform.parent.childCount;
        int myIndex = transform.GetSiblingIndex();
        Vector3 newPosition = CalculateCirclePosition(player.position, radius, numberOfFireballs, myIndex);
        transform.position = newPosition; // 设置小球的初始位置
    }

    // 计算小球在圆周上均匀分布的位置
    Vector3 CalculateCirclePosition(Vector3 center, float radius, int totalPoints, int currentIndex)
    {
        angle = (360.0f / totalPoints) * currentIndex;
        float radians = angle * Mathf.Deg2Rad;
        float x = center.x + radius * Mathf.Cos(radians);
        float y = center.y + radius * Mathf.Sin(radians);

        return new Vector3(x, y, center.z);
    }
}

成为某个物体的子集

后面会自动分配角度,围绕主角旋转

相关推荐
nnsix1 天前
Unity OpenXR开发HTC Vive Cosmos
unity·游戏引擎
nnsix1 天前
Unity OpenXR,扳机键交互UI时,必须按下扳机才触发
unity·游戏引擎
nnsix1 天前
Unity XR 编辑器VR设备模拟功能
unity·编辑器·xr
老朱佩琪!1 天前
Unity访问者模式
unity·游戏引擎·访问者模式
不定时总结的那啥1 天前
Unity实现点击Console消息自动选中预制体的方法
unity·游戏引擎
nnsix1 天前
Unity OpenXR 关闭手柄的震动
unity·游戏引擎
CreasyChan1 天前
Unity 中的反射使用详解
unity·c#·游戏引擎·游戏开发
Jessica巨人1 天前
Shader显示为黑色
unity·shader
天途小编1 天前
无人机操控模式解析:美国手、日本手、中国手
游戏引擎·无人机·cocos2d
BT-BOX2 天前
普中开发板基于51单片机贪吃蛇游戏设计
单片机·游戏·51单片机