- Home /
Drag 0, 90, 180 or 270 degrees from first object
First let me explain what I already have.
The placementNode (The gameobject what follows the mouse) follows the mouse on a (temporary) 32*32 grid. When you click, the newNode (the gameobject what is used to place the road) is instantiate at the x and z position of the mouse. Therefore I use the following code:
#pragma strict
var gridSize : int = 32;
var nodePrefab : Transform;
private var rayHitWorldPosition : Vector3;
function Update () {
var rayHit : RaycastHit;
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), rayHit))
{
// where did the raycast hit in the world - position of rayhit
rayHitWorldPosition = rayHit.point;
var xPos = Mathf.Floor(rayHit.point.x / gridSize) * gridSize;
var zPos = Mathf.Floor(rayHit.point.z / gridSize) * gridSize;
}
transform.position.x = xPos;
transform.position.z = zPos;
if(Input.GetMouseButton(0)){
var newNode = Instantiate(nodePrefab, Vector3(xPos,transform.position.y,zPos), Quaternion.identity);
}
}
This code works perfect for me. But now comes the question,
When the nodePrefab is instantiated, you have to 'drag' to a direction. The length doesn't matter. But I want that you can only drag in a straight line, so only in 0, 90, 180 or 270 degrees from the nodePrefab.

Red: nodePrefab (First instantiated on mouseclick) Grey: Dragged from red. Can be dragged in all directions. Light blue: This is NOT how it should be.
Can someone advise me on how to do this?
Answer by Jeffuk · Oct 08, 2014 at 03:03 PM
Could you store the 'lastXPos' and 'lastYPos' and check that one of them is the same before drawing.
if(Input.GetMouseButton(0) && (xPos==lastXPos || yPos==lastYPos)){
var newNode = Instantiate(nodePrefab, Vector3(xPos,transform.position.y,zPos), Quaternion.identity);
lastXPos = xPos;
lastYPos = yPos;
}
Edit: You'll have to do something different the first time you click.. so you could set both to -1 on mouseUp to allow you to click somewhere new.. like if(Input.GetMouseButton(0) && (xPos==lastXPos || yPos==lastYPos)){
Answer by Scribe · Oct 08, 2014 at 03:36 PM
Just check which one of the two vector components is larger and move in that direction:
dragDir = mousePosition - originalMousePosition;
dragDir.x = Mathf.Abs(dragDir.x) > Mathf.Abs(dragDir.z) ? dragDir.x : 0;
dragDir.z = Mathf.Abs(dragDir.x) > Mathf.Abs(dragDir.z) ? 0 : dragDir.z;
//Instantiate at dragDir
Hope that helps!
Scribe
Your answer
Follow this Question
Related Questions
Transform angle to grid position 2 Answers
Switching between areas in a scene with triggers 0 Answers
Grid-based movement: How to face forward 2 Answers
how do i create a "randomized infinite grid"? details here.. 2 Answers
Is there a toggle for snap to grid? 10 Answers