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

成为某个物体的子集

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

相关推荐
郝学胜_神的一滴12 小时前
游戏设计:原型与开发 06:读懂游戏设计最容易被忽略的文化层
游戏·游戏开发
GoWjw17 小时前
RK3288 游戏盒子安卓 5.1 线刷包说明
游戏
年少无知且疯狂17 小时前
【Unity】Shader spine动画冻结效果
unity·spine
淡海水18 小时前
05-02-源码-Boehm GC标记阶段
算法·unity·c#·游戏引擎·gc
2601_9496955920 小时前
3DM游戏运行库合集安装教程,缺少DLL文件这样修复
windows·游戏·电脑
笨鸟先飞的橘猫1 天前
skynet——RPC 超时机制优化方案
游戏·rpc·skynet
淡海水1 天前
05-03-源码-Boehm GC分配与碎片管理
开发语言·算法·unity·c#·游戏引擎·gc
奥列格2 天前
《神探杰克:导演剪辑版》steam Windows版汉化补丁
游戏
全速向光2 天前
Game Cheats Manager 使用教程:开源的单机游戏修改器聚合管理方案
游戏
河南花仙子科技2 天前
古镇非遗小游戏如何传播传统文化
游戏