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.

Topdown example

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?

2 Answers

2

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)){

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