LoginSignup
1
0

More than 5 years have passed since last update.

Unityでのプレハブの座標について(ワールド座標とローカル座標)

Last updated at Posted at 2019-03-02

疑問に思ったこと

Unityでプレハブで敵を配置しているときにそれぞれの位置座標を変えていて思いました.
あれ?自分の入力している値と表示される場所に違いがあるのではないのか?
これはなぜだろう・・ってことでなぜに一致しないのか,どうするべきなのかについて考えていきたいと思います.

こちらが今回使っているスクリプトの一部です.

enemy.cs
    public class enemy : MonoBehaviour
    {
    public float position_x = 0.0f;
    public float position_y = 0.0f;
    [Range(0.0f,3.0f)]
    public float rotation_speed = 1.0f;
    [Range(1.0f,10.0f)]
    public float rotation_range = 1.0f;

    // Update is called once per frame
    void Update()
    {
        if(gameObject.layer == 9){
            move_lengh();
            // Debug.Log("lengh");
        }else if(gameObject.layer == 10){
            move_side();
            // Debug.Log("side");
        }
    }

    void move_lengh(){
        float pos_x = this.gameObject.transform.position.x;
        float pos_y = this.gameObject.transform.position.y;
        float sin = Mathf.Sin(rotation_speed*rotation_range*Time.time) + position_y;
        Debug.Log("eagle->"+"pos_x:"+this.gameObject.transform.localPosition.x+",pos_y"+this.gameObject.transform.localPosition.y+",sin:"+sin);
        this.transform.position = new Vector3(pos_x,sin,0);
    }

スクリーンショット 2019-03-02 18.32.16.png

(自分が作成したいるスクショなのでわかりづらいところもありますが,御料所ください)
ここで見てきたいのは,赤くなっているところの二つになります.

何が知りたいか

では,コードとスクショの方を見比べていきます.


        float pos_x = this.gameObject.transform.position.x;
        float pos_y = this.gameObject.transform.position.y;

この二つのコードはそれぞれのオブジェクトの座標を取得します.では,この座標とスクショの右上の値を比べてみます.この時に得られる座標はワールド座標になります.(こちらはスクショを取っていません)
では,この座標をスクショの右上と同じ値を得るためにはどのようにすればいいのでしょうか.
その場合は,以下のようにします.ワールド座標ではなくローカル座標を得るといいことがわかりました.


Debug.Log("eagle->"+"pos_x:"+this.gameObject.transform.localPosition.x+",pos_y"+this.gameObject.transform.localPosition.y+",sin:"+sin);

これでターミナルに表示される値とUnity上に表示される値は同じになりました.

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0