Unity:无论位置如何变化,GameObject 始终位于中心

Unity: GameObject always at center regardless of position changes

我正在开发一款 2D 游戏,并使用 C# 脚本创建了一个游戏对象,如下所示。我还将我的相机设置为正交,并根据屏幕的宽度调整了我的精灵。无论我设置的位置如何,对象始终位于屏幕的中心。我该如何解决?

using UnityEngine;
using System.Collections;

public class TestingPositions : MonoBehaviour {

 GameObject hero;
 Sprite heroSprite;
 Vector3 heroPosition;
 // Use this for initialization
 void Start () {

       hero = new GameObject ();
       Instantiate (hero, heroPosition, Quaternion.identity);
     Camera camera = GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<Camera> ();
     heroPosition = camera.ScreenToWorldPoint(new Vector3(Screen.width/4, Screen.height/4, camera.nearClipPlane));
     heroSprite = Resources.Load <Sprite> ("Sprites/heroImage");
     SpriteRenderer renderer = hero.AddComponent<SpriteRenderer>();        renderer.sprite = heroSprite;
 }
}

当你使用实例化时,你必须在

上使用它

现有模型。

实例化的意思是“复制这个模型”或“复制这个模型”,或“制作一个新模型,以此模型为例”。

您正在做的是创建一个全新的空“英雄”游戏对象,然后“实例化”它。那是没有意义的,什么也不做。

每当你想使用“实例化”时,你必须做的是:

 public GameObject modelPerson;

请注意名称必须为“modelSomething”。

首先将其放入您的代码中。看看检查员。制作您真正的英雄模型(或其他)

把它放在镜头外看不见的地方。

现在,将那个东西拖到检查器中的“modelPerson”槽中。

如果您不熟悉在 Unity 中使用 Inspector-dragging 的基础知识,请查看基本的 Unity 教程 https://unity3d.com/learn/tutorials/topics/scripting

接下来在您的代码中,也许在“开始”中,试试这个

GameObject newHero = Instantiate( modelPerson );
newHero.transform.position = .. whatever you want
newHero.transform.rotation = .. whatever you want
newHero.name = "Dynamically created";
newHero.transform.parent = .. whatever you want

一旦你了解了这些基础知识,关于 Instantiate 的知识还有很多。您可以在单独的问题中提出这个问题。祝你好运。

  1. 您需要保存对使用 Instantiate 创建的 gameObject 的引用,because Instantiate makes a copy not modifies the original
  2. 要在实例化后修改游戏对象的位置,您需要使用gameobject.transform.position = newPosition;要在实例化之前修改它,您需要在实例化中使用 heroPosition 之前执行 "heroPosition" 行。

像这样:

using UnityEngine;
using System.Collections;

public class TestingPositions : MonoBehaviour
{

GameObject hero;
SpriteRenderer heroSprite;
// Use this for initialization
void Start()
{
    Camera camera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();

    //Save the reference to the instantiated object into a variable
    //Since you are creating an object from scratch, you don't even need Instantiate, which means copy - not create.
    hero = new GameObject();
    //Set its position
    hero.transform.position = camera.ScreenToWorldPoint(new Vector3(Screen.width / 4, Screen.height / 4, camera.nearClipPlane));
    //Set its rotation
    hero.transform.rotation = Quaternion.identity;
    //Add sprite renderer, save the reference
    heroSprite = hero.AddComponent<SpriteRenderer>();
    //Assign the sprite
    heroSprite.sprite = Resources.Load<Sprite>("Sprites/heroImage");
 }
}