统一性:无论位置如何变化,GameObject始终居中 [英] Unity: GameObject always at center regardless of position changes

查看:80
本文介绍了统一性:无论位置如何变化,GameObject始终居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a 2D game and have created a game object using C# script as below. I also set my camera to orthogonal and have adjusted my sprite based on the width of the screen. Regardless of the position I set, the object is always at the center of the screen. How can I solve this?

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

推荐答案

使用实例化时,您必须在

实例化是指复制此模型".或复制此模型",或以该模型为例,制作一个新模型".

Instantiate means "duplicate this model" or "copy this model", or "make a new one, using this model as an example".

您正在做的是创建一个全新的空白英雄"商品,游戏对象-然后实例化"它.那是没有意义的,什么也没做.

What you are doing, is creating a brand new empty "hero" game object - and then "instantiating" it. That is meaningless and does nothing.

无论何时要使用实例化",都必须执行什么操作?是这个吗?

What you must do whenever you want to use "Instantiate" is this:

 public GameObject modelPerson;

请注意,名称必须必须是"modelSomething".

Note that the name must be "modelSomething".

首先将其放入您的代码中.在检查员处查看.使您成为真正的模特英雄(或其他角色)

first put that in your code. LOOK at the Inspector. MAKE your actual model hero (or whatever it is)

将其放在相机看不到的地方.

Sit it somewhere off camera where it is not seen.

现在,将其拖动到"modelPerson"检查器中的插槽.

Now, drag that thing to the "modelPerson" slot in the Inspector.

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

If you are not familiar with the basics of using Inspector-dragging in Unity, review basic Unity tutorials https://unity3d.com/learn/tutorials/topics/scripting

接下来在您的代码中,也许在开始"中,尝试此操作

Next in your code, perhaps in Start, try this

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的知识.您可以在单独的问题中提问.祝你好运.

once you understand these basics, there is very much more to learn about Instantiate. You can ask that in separate questions. Good luck.

这篇关于统一性:无论位置如何变化,GameObject始终居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆