Skip to content

Unity Resource: XYMouseController

May 10, 2010
tags:

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.

Click here to see the code in action.

Here’s the Unity3D project for the above example. 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)
Advertisement
No comments yet

Leave a Reply

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

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

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

Facebook photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.