Mingan Beyleveld
Mingan Beyleveld

Reputation: 281

Rotate an object according to terrain in Unity (C#)

I currently have an item placement system for building. It works by instantiating a "ghost" of the object that shows where it can be placed, the ghost (semi-transparent) object is attached to the camera and instantiates the object in its place when the player clicks.

I get the position at which to keep the ghost object like so:

        var pos = transform.position + transform.forward * placeDistance;  // A position 'someDistance' in front of the player
        pos.y = Terrain.activeTerrain.SampleHeight(pos);  // Get the position at the surface of the terrain to place the object
        firePlaceable.transform.position = pos + Vector3.up * 0.001f;  // 'halfHeight' is used in case the pivot is not on the base

Now.. I need the object to rotate according to the terrain so that the fire place is placed more or less correctly rotated. Any ideas? What would the best plan be?

Upvotes: 2

Views: 5600

Answers (1)

Piranha
Piranha

Reputation: 919

Use the terrain normal vector at the place' position.

For example you could do a raycast straight down from the fireplace. The resulting hit contains a normal that is your place' up vector.

By thinking of it... I assume you already doing a raycast to get the position to place the fireplace right?

Use the placement raycast to get the up vector instead of making a new one.

So basicly do

fireplace.transform.up = clickPlaceHit.normal;

Upvotes: 1

Related Questions