Mike IGEG
Mike IGEG

Reputation: 11

How to get two gameobjects to face each other using scripting in Unity3D

I am in the process of creating a chess game and I want to have the white team pieces (0-5 in an array) and black team pieces (6-11 in the array) face each other on the chessboard. I manage to get them to spawn but currently I have only managed to get them all facing in the same direction.

I have tried adjusting the Y rotation transform in the inspector but want to achieve it programmatically in the script if possible.

I am using this code to set orientation of all pieces:

private Quaternion orientation = Quaternion.Euler(0, 180, 0);

And this code to spawn the chess pieces to the chessboard:

private void SpawnChessMan (int index, int x, int y)
{

    GameObject go = Instantiate(ChessManPrefabs[index], GetTileCenter (x,y) , orientation) as GameObject;
    go.transform.SetParent(transform);
    ChessMans[x, y] = go.GetComponent<ChessMan>();
    ChessMans[x, y].SetPosition(x, y);
    ActiveChessMan.Add(go);
}

The code does what I expect, but how do I have them face each other using c# for Unity3D?

Upvotes: 1

Views: 326

Answers (2)

kevernicus
kevernicus

Reputation: 364

You could use your board x/y coordinates to determine the initial rotation of your pieces. Let's assume your white is on the left in columns x = 1 to 2, and black on the right in columns x = 7 to 8.

Facing the right side is your original rotation of (0, 180, 0).

Then you could change your code as follows:

Quaternion rot = Quaternion.Euler(0, (x < 3? 180: -180), 0);
GameObject go = Instantiate(ChessManPrefabs[index], GetTileCenter (x,y) , rot) as GameObject;

Upvotes: 1

Louis Ingenthron
Louis Ingenthron

Reputation: 1368

Unity has a bunch of useful tools if you know where to look.

https://docs.unity3d.com/ScriptReference/Transform.LookAt.html

Upvotes: 2

Related Questions