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

成为某个物体的子集

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

相关推荐
淡海水2 小时前
【节点】[ScleraLimbalRing节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·ring·limbal·sclera
~央千澈~3 小时前
抖音弹幕游戏开发之第14集:添加更多整蛊效果·优雅草云桧·卓伊凡
开发语言·python·游戏
开开心心_Every4 小时前
局域网大文件传输,设密码双向共享易用工具
运维·服务器·网络·游戏·pdf·电脑·excel
ellis19707 小时前
Unity特殊目录小结
unity
向晚向晚,理智性感7 小时前
win+G唤醒游戏录制没反应怎么开启
游戏·快捷键·xbox·xbox game bar
三雷科技7 小时前
人工智能系统学习知识点:游戏辅助工具开发
人工智能·学习·游戏
淡海水1 天前
【节点】[IrisOutOfBoundColorClamp节点]原理解析与实际应用
unity·游戏引擎·iris·shadergraph·图形·clamp·bound
独自破碎E1 天前
BISHI53 [P1080] 国王游戏(简化版)
android·java·游戏
风痕天际1 天前
Godot扫雷游戏制作记录1——基础场景搭建
游戏·游戏引擎·godot·gdscript·教程