Trying to make a tractor beam

I’m trying to make a tractor beam using RayCast. The Ray works but I can’t figure out how to make the objects come to me. How can I make the objects I tag move towards the player using the ray?

var MyColor : Color = Color.red;
var target : Transform;
var come : float = 5;

function Awake()
{
    target = gameObject.Find("Player").transform;
}

function Start()
{
	Screen.showCursor = false; 
}

function Update () 
{
	if(Input.GetButton("Fire1"))
	{
// Get the ray going through the center of the screen
		var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
// Do a raycast
		var hit : RaycastHit;
		if (Physics.Raycast (ray, hit,100))
		{
			if(hit.collider.gameObject.tag == "Pullable")
			{
				transform.position = Vector3.MoveTowards(transform.position, target.position,Time.deltaTime * 5);
				transform.LookAt(target);
				print ("I'm looking at " + hit.transform.name);
			}
		}
		else
		{
			print ("I'm looking at nothing!");
		}
		Debug.DrawLine (ray.origin, hit.point, Color.red);
	}
}

The code you have here makes the object this Script is attached to move towards the the object hit by the ray. It should be as simple as swapping the transforms that you are affecting.

1 Answer

1

As @Silver Tabby said, you’re using the wrong transforms:

var MyColor : Color = Color.red;
var target : Transform;
var come : float = 5;

function Awake()
{
    target = gameObject.Find("Player").transform;
}

function Start()
{
	Screen.showCursor = false; 
}

function Update () 
{
	if(Input.GetButton("Fire1"))
	{
// Get the ray going through the center of the screen
		var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
// Do a raycast
		var hit : RaycastHit;
		if (Physics.Raycast (ray, hit,100))
		{       // if the object hit is Pullable...
			if(hit.transform.tag == "Pullable")
			{       // move the object hit!
				hit.transform.position = Vector3.MoveTowards(hit.transform.position, target.position, Time.deltaTime * 5);
				// makes the object hit look to the target    
				hit.transform.LookAt(target);
				print ("I'm looking at "+hit.transform.name);
			}
		}
		else
		{
			print ("I'm looking at nothing!");
		}
		// you will have no hit.point if nothing was hit - use DrawRay instead    
		Debug.DrawRay (ray.origin, ray.direction * 100, Color.red);
		// but since the ray starts at the center of the viewport, you will    
		// only see a red dot anyway.
	}
}

NullReferenceException: Object reference not set to an instance of an object TractorBeam.Awake () (at Assets/SCRIPTS/TractorBeam.js:7)

Then you don't have an object in your scene named Player search NullReferenceException If there is no gameObject found named Player, the transform cannot be accessed. The gameObject returns a null.