- Home /
Snap Objects when Spawning
Hey all, im having trouble snapping my objects together when they hit. like, im tryna make it so that when i spawn one near another, it doesnt go into it but rather next to or on.. anyone got a good solution?
var cubeobj : Transform;
function Update () {
var mousex = Input.mousePosition.x;
var mousey = Input.mousePosition.y;
var mousez = Input.mousePosition.z;
var ray = camera.main.ScreenPointToRay(Vector3(mousex,mousey,mousez));
var hit : RaycastHit;
if(Physics.Raycast (ray, hit, 200)) {
}
if ( Input.GetButtonDown("Fire1") ){
var cube = Instantiate(cubeobj, hit.point, Quaternion.identity);
}
}
Not related to the answer, but why split the xy(Z?) of mouse.pos and then rebuild it as a Vector3 (which it already was) into the input of ScreenPointToRay? Did you try:
ScreenPointToRay(Input.mousePosition)
Do your cubes have a collider/trigger on them?
If you're working with Unity's cubes, you'll need to offset them from the hit.point by adding hit.normal * (size of the cube).
With some code refactoring to show you a more efficient way to do what you want, here's an example:
var cubeobj : Transform;
function Update() {
if ( Input.GetButtonDown("Fire1") ){ //this if statement is quicker to check, so do it first to avoid doing a raycast even when the user hasn't clicked
var ray = Camera.main.ScreenPointToRay(Input.mousePosition); //as getyour411 suggested
var hit : RaycastHit;
if(Physics.Raycast (ray, hit, 200)) {
var spawnPoint : Vector3 = hit.point + hit.normal * 0.5f;
//the above line assumes your cube is 1 unit wide,
//and has its origin at its centre (hence
//offsetting it by half its width)
//spawn the cube
var cube = Instantiate(cubeobj, spawnPoint, Quaternion.identity);
//note that how you offset objects from one another
//will need to change depending on what shape your object is
}
}
}
but then i get this error: NullReferenceException UnityEngine.Camera.ScreenPointToRay (Vector3 position) InputHandler.Update () (at Assets/InputHandler.cs:20)
Your answer
Follow this Question
Related Questions
Destroy Istantiated objects after some time (different for each instance) 1 Answer
Question Local Translation PRoblem 2 Answers
move particle direction with player 1 Answer
repeat object spawn 3 Answers
AI Help FPS 0 Answers