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);
    }
}

成为某个物体的子集

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

相关推荐
程序猿多布7 小时前
预定义委托(C# and Unity)
unity·c#
虾球xz9 小时前
游戏引擎学习第108天
学习·游戏引擎
虾球xz10 小时前
游戏引擎学习第112天
java·学习·游戏引擎
Edision_li16 小时前
DeepSeek教unity------Dotween
unity·游戏引擎
zfoo-framework17 小时前
Unity中NavMesh的使用 及其 导出给java服务端进行寻路
unity
程序猿多布17 小时前
数学函数(C#、Lua 、Unity)
unity·c#·lua
TheFirst00818 小时前
The First项目报告:重塑链上游戏生态,解读B3 Base的双赢局面
游戏
虾球xz19 小时前
游戏引擎学习第110天
数码相机·学习·游戏引擎
爱写代码的山山1 天前
虚幻蓝图解决抗锯齿方案
游戏·ue5·游戏引擎·虚幻·抗锯齿化
github_czy1 天前
(9/100)每日小游戏平台系列
javascript·python·游戏引擎·游戏程序