This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
TVdata's profile picture

How do I get left and right directions from a direction?

Started by TVdata, 01 January 2016 - 02:54 PM
TVdata #1
Posted 01 January 2016 - 03:54 PM
I need to get left and right directions (in global) based on a direction. How do I do it?
Exerro #2
Posted 01 January 2016 - 04:45 PM
Do you mean find the direction to the left and right of where you're currently heading? Are you using north/south/east/west as directions or (+/-)1 for x and y (or more dimensions)?

Assuming this is probably a turtle thing, you'll be dealing with north, south, east and west. This should work:


local directions = {"north", "east", "south", "west"}
local direction = "east"

local function getRight() -- returns the direction to the right of the current direction (defined by the 'direction' variable)
	for i = 1, #directions do
		if directions[i] == direction then
			return directions[i % 4 + 1]
		end
	end
end
local function getLeft() -- returns the direction to the left of the current direction (defined by the 'direction' variable)
	for i = 1, #directions do
		if directions[i] == direction then
			return directions[i == 1 and 4 or i - 1]
		end
	end
end
Edited on 01 January 2016 - 03:47 PM
TVdata #3
Posted 01 January 2016 - 06:08 PM
I meant a vector. I am trying to calculate positions for turtles based on single point and direction. Thank you for that code, I will definitely use that too.

EDIT: I'm just going to use that and transform the directions to vectors.
Edited on 01 January 2016 - 05:23 PM
Exerro #4
Posted 01 January 2016 - 07:40 PM
With vectors, you can do this:


local function rotateAnticlockwise( x, y ) -- also known as left 90 degrees
	return -y, x
end
local function rotateClockwise( x, y ) -- also known as right 90 degrees
	return y, -x
end

Edit: just to clarify, positive Y would be forward and positive X would be right.
Edited on 01 January 2016 - 06:44 PM