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

成为某个物体的子集

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

相关推荐
老朱佩琪!4 小时前
Unity原型模式
开发语言·经验分享·unity·设计模式·原型模式
老朱佩琪!4 小时前
Unity组合模式
unity·游戏引擎·组合模式
老朱佩琪!4 小时前
Unity装饰器设计模式
unity·设计模式
九影网络5 小时前
虚实游戏怎么选?详解AR与VR游戏的核心区别
游戏·ar·vr
向宇it5 小时前
【unity游戏开发——网络】unity对接steam,并上传发布游戏版本——Steamworks.NET
游戏·unity·游戏引擎·.net·交互
陈言必行5 小时前
Unity 实战:屏蔽移动平台 UI 点击检测的“坑”与解决之道
ui·unity·游戏引擎
CreasyChan5 小时前
unity-向量数学:由浅入深详解
unity·c#
nnsix5 小时前
Unity Terrain获取关联的TerrainData
unity·游戏引擎
秦奈5 小时前
Unity复习学习笔记(七):NGUI
笔记·学习·unity
Sui_Network5 小时前
社交游戏 Super-B 登陆 Epic 游戏商店抢先体验
人工智能·游戏·rpc·区块链·量子计算