- Home /
Drag Rigidbody into slots?
Hi - i know there are several questions like this, but none of them have a conclusive answer, and the only one that i could see and answer to has a broken link, in french, so i can't see it:
http://answers.unity3d.com/questions/204483/create-grid-and-snap-rigidbodies-to-grid.html
anyway, I have a 2D sprite based game, where you click on the objects you want to choose from the HUD and they spawn in the play area, I have a drag rigid body script on them and it works fine, no problems.
However, i now think it would be better if the drag rigid body script worked in increments, i would have a grid on the background, and the drag wouldn't be smooth, but would snap into the positions, each equally separated.
One way i could think of would be to put empty game objects on each point with a trigger area, and add a script on each trigger to say:
function OnTriggerEnter(){
draggedRigidbody.transform.position = this.transform.position
}
etc,
BUT i think this is extremely complicated as every level will have a different shaped grid, and i don't want to have 30 triggers with scripts and have to set them up each level.. would there be a better way to go about this?
thanks in advance, by the way if there are any code samples posted, could they be in JS please.. still need to get round to start programming in C :p
Answer by easilyBaffled · Jun 02, 2012 at 03:24 PM
This is my full implementation of Click and Drag and Snap to Place. The Snapping bit takes place in the OnMouseUp section, basically, find the center of each slot on the grid, find the location of your Object and subtract from its position to get it to the closest center.
var moving = false;
var posX : float;
var posY : float;
var ray : Ray;
function Update () {
if(moving == true){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
transform.position.x = ray.GetPoint(14).x;
transform.position.y = ray.GetPoint(14).y;
transform.position.z = 1.1;
}
}
function OnMouseDown () {
moving = true;
}
function OnMouseUp () {
//if out of bounds destroy it
if(transform.position.x > 1.5 || transform.position.x < -10.5 || transform.position.y > 9.5 || transform.position.y < -.5){
Destroy(gameObject);
}
moving = false;
//Snap to feature
posX = transform.position.x;
posX = Mathf.Round(posX);
if(posX > transform.position.x){
posX--;
}
posY = transform.position.y;
posY = Mathf.Round(posY);
if(posY > transform.position.y){
posY--;
}
transform.position.x = posX +.5;
transform.position.y = posY +.2;
}
sorry for the late reply, i ended up going in a different direction and not implementing this at all, now i haven't tested your script but the logic makes sense, thanks for the answer, this may come in handy in the future :P :)
Answer by BigBlob · Jul 27, 2012 at 02:18 PM
In fact I speak french not very much but I accidentaly found the Download button so heres the direct link to it, tell me if it doesn not work!
Felipe