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 小时前
【Unity开发】Rigidbody中Body Type属性
unity·游戏引擎·unity开发
winlife_7 小时前
AI 怎么验证 Unity PlayMode 行为:截图 + 输入模拟的完整闭环
人工智能·unity·游戏引擎·ai编程·claude·playmode
数智工坊9 小时前
【深度学习RL】DQN:深度强化学习的里程碑——让AI从像素中学会玩Atari游戏
论文阅读·人工智能·深度学习·游戏·transformer
2601_956002819 小时前
gta侠盗猎车手5 2026最新绿色破解版免费下载 pc版 手机版通用
游戏·智能手机·游戏程序·团队开发·游戏美术·数字雕刻·关卡设计
CandyU210 小时前
Cursor AI Unity
unity
LF男男10 小时前
Bullect.cs(bullet)——子弹基类
unity
德迅云安全-小潘10 小时前
游戏行业如何保障网络安全
服务器·网络·游戏
上海云盾第一敬业销售10 小时前
游戏开服即“炸服“?CC攻击成游戏行业隐形杀手
服务器·网络·游戏
资源分享助手19 小时前
小马游戏 Horsey Game 下载与介绍(老番茄推荐)
游戏
mxwin1 天前
unity shader中 ddx ddy是什么
unity·游戏引擎·shader