Unity Resource: XYMouseController

Unity LogoHere’s a companion to the XYController example. It demonstrates translating the mouse’s screen coordinates into a point in Unity world space, and using this to position an object. (Translation: it allows a player to move an object around with the mouse.)

It isn’t game-ready, but it’s simple and (hopefully) easy to understand.

Here’s a sample Unity3D project. And here’s the source code for the XYMouseController script, which is attached to the capsule.

XYMouseController.js

#pragma strict

// FixedUpdate is a built-in unity function that is called every fixed framerate frame.
// According to the docs, FixedUpdate should be used instead of Update when dealing with a
// Rigidbody.
// See http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.FixedUpdate.html
// for more information.
function FixedUpdate () {
	var mousePos = Input.mousePosition;

	var worldPos = camera.main.ScreenToWorldPoint(
		Vector3(
			mousePos.x,
			mousePos.y,
			Mathf.Abs(transform.position.z - camera.main.transform.position.z)
		)
	);

	var newPos = Vector3(
		worldPos.x,
		worldPos.y,
		transform.position.z
	);

	// Move the object
	rigidbody.MovePosition(newPos);
}

// Require a Rigidbody component to be attached to the same GameObject.
@script RequireComponent(Rigidbody)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s