I would like to know if it is possible to use the face of an object (for example let's name it Object 1) and use the face as a target to position another object (Object 2) side by side, using the face of Object 2 as the second target.
Let's say that I have three simple box-like objects and I want to make different compositions by adding to the first object, already present in the scene, another one and then the other in whatever order i want by pressing a specific key on the keyboard (let's say W key for the Object 2 and S key for the Object 3).
It doesn't need to be with this method that I thought, but it needs to be the same process. It should take into consideration the size of the object and also the rotation.
CodePudding user response:
One possible solution is to carfully make prefabs of your shapes in a way that would allow you to instantiate them so that they are aligned correctly.
The following overview shows your three shapes saved as prefabs. They have been constructed using an Empty GameObject
(blue diamond) and attaching the 3d model (works for sprites as well) and placing another Empty GameObject
(red diamond) that is rotated so that the green axis arrow points in the direction of the normal.
If you attach the following script to the red diamond Empty GameObject
and put the prefabs in their slots, you will be able to instantiate shapes 2 and 3 by pressing S
and W
respectively.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Placement : MonoBehaviour
{
public GameObject shape1, shape2, shape3;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
Instantiate(shape3, transform.position, transform.rotation);
this.enabled = false;
}
if (Input.GetKeyDown(KeyCode.S))
{
Instantiate(shape2, transform.position, transform.rotation);
this.enabled = false;
}
}
}
Note that the script also disables itself upon a successful instantiation, so that it only spawns shapes at the very end.