Example 2 - Randomly positioning objects

Code

<scene>
  
	<object type="primitives://plane.aro" id="myplane" scale="0.2 0.2 0.2">
		<event type="onclickdown">
			<runscript type="text/x-lua" code="moveThePlane()"/>
		</event>
	</object>
  
	<script type="text/x-lua">
	<![CDATA[ 
	
		-- This example builds upon Example 1 to include functionality
		-- only available in Lua
	
		myplaneObject = scene:getById("myplane")
	
		function moveThePlane()
	
			-- math.random() returns a random number distributed
			-- between 0 and 1
			-- We need to perform some arithmetic to change our
			-- random X and Y values to be between -1 and 1
			local randomX = math.random() * 2 - 1
			local randomY = math.random() * 2 - 1
			local myNewPosition = {randomX, randomY, 0}
		
			myplaneObject:setPosition(myNewPosition)
	
		end
	]]>
	</script>
</scene>

Analysis

As in the previous example, the plane object is found in the scene when it starts, then a runscript node is used to run a function. This time, the function moves the plane to a random position in the scene when the user clicks on it.

The use of math.random means that it is not possible to create this functionality using action nodes alone.