【问题标题】:Unity Setting parents gameObjects transform into the childs transform variables?Unity设置父母gameObjects变换成childs变换变量?
【发布时间】:2019-01-24 14:08:46
【问题描述】:

有没有好的方法可以做到这一点,我在下面复制了我的代码。这是我的代码,以便游戏对象在地图的某个区域周围巡逻,我需要一种方法,以便在生成敌人时设置相对于生成敌人的游戏对象的变换。

当我从预制件中生成敌人时,敌人应该在生成它的生成点周围巡逻,但是我在游戏中有多个生成敌人的点。巡逻脚本有一个转换 public Transform moveSpots;我将生成点对象分配给。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Patrol0 : MonoBehaviour
{
    public float speed;
    public Transform moveSpots;
    private float waitTime;
    public float StartwaitTime;
    public float MinX;
    public float MaxX;
    public float MinY;
    public float MaxY;
    void start()
    {
        moveSpots = GetComponentInParent<Transform>();
        waitTime = StartwaitTime;
        moveSpots.position = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxX));
    }
    private void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, moveSpots.position, speed * Time.deltaTime);
        if (Vector2.Distance(transform.position, moveSpots.position) < 0.2f)
        {
            if (waitTime <= 0)
            {
                moveSpots.position = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxX));
                waitTime = StartwaitTime;
            }
            else
            {
                waitTime -= Time.deltaTime;
            }
        }
    }
}

【问题讨论】:

  • 嗨,亚当。欢迎来到 Stackoverflow!如果您将代码添加到您的问题而不是屏幕截图中,我们会更容易。
  • 你能解释一下你拥有什么以及你想得到什么吗?
  • gameObject.transform.parent 将为您提供子组件的父变换。
  • 你的意思是像parentObject.transform.SetParent(childObject.transform);
  • 如果您将代码添加为文本将是很棒的 ..

标签: c# unity3d


【解决方案1】:

假设生成的对象也成为生成对象的父对象,您可以将所有 transform.position 引用替换为 transform.localPosition。如果没有,您可以使用从生成器的转换中调用的Transform.TransformPoint()

Transform Spawner;

void start()
{
    moveSpots = GetComponentInParent<Transform>();
    waitTime = StartwaitTime;
    moveSpots.position = new Vector2(Random.Range(MinX, MaxX), Random.Range(MinY, MaxX));
    moveSpots.position = Spawner.TransformPoint(moveSpots.position);
}

这将获取本地空间 moveSpots.position 并将其转换为相对于 Spawner 的世界空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2019-06-03
    • 2013-10-08
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多