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

成为某个物体的子集

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

相关推荐
电报号dapp11926 分钟前
全链游戏模式:自治世界与AI增强型交互
人工智能·游戏·web3·去中心化·区块链·智能合约
oyishyi3 小时前
从零开始独立游戏开发学习笔记(七十八)--绘画/像素画学习笔记(十五)--V大预科3.0(五)-第三,四周理论
游戏·游戏开发
FakeOccupational18 小时前
【碎碎念】宝可梦 Mesh GO : 基于MESH网络的口袋妖怪 宝可梦GO游戏自组网系统
网络·游戏
XR-AI-JK18 小时前
Unity VR/MR开发-VR/开发SDK选型对比分析
unity·vr·mr
从零开始学习人工智能1 天前
从游戏到自动驾驶:互联网时代强化学习如何让机器学会自主决策?
人工智能·游戏·自动驾驶
心之所向,自强不息1 天前
【Unity Shader编程】之让画面动起来
unity·游戏引擎
豆沙沙包?2 天前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
程序员大辉2 天前
游戏常用运行库合集 | GRLPackage 游戏运行库!
游戏
不伤欣2 天前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
Magnum Lehar2 天前
vulkan游戏引擎test文件memory实现
游戏引擎