- Home /
camera.ScreenToWorldPoint() question
I'm trying to convert the Vector data from Input.mousePosition() relative to the playing screen. It works without the camera.ScreenToWorldPoint line but not properly. However, it doesn't work at all with that line in, saying I need to a attach a camera (there is one as a child to the player).
Here's my code thus far:
var speed = 6.0; var jumpSpeed = 8.0; var gravity = 20.0; var mousePosition; var AllowClickJump : boolean = true; var clickJump : float = 2; private var moveDirection = Vector3.zero; private var grounded : boolean = false;
function Awake() { clickJump = clickJump/10; }
function FixedUpdate() {
if (grounded) {
// We are grounded, so recalculate movedirection directly from axes
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
// mouse jump
/* HERE IS WHERE MY PROBLEM IS */
if (Input.GetButtonDown ("Fire1") && AllowClickJump)
{
mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
//THIS LINE RIGHT HERE kills the script, saying I need
//to attach a camera.
mousePosition = camera.ScreenToWorldPoint(mousePosition);
mousePosition = transform.TransformDirection(mousePosition);
moveDirection = mousePosition;
moveDirection *= clickJump;
}
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
var controller : CharacterController = GetComponent(CharacterController);
var flags = controller.Move(moveDirection * Time.deltaTime);
grounded = (flags & CollisionFlags.CollidedBelow) != 0;
}
@script RequireComponent(CharacterController)
Answer by Jessy · Jun 16, 2010 at 02:03 AM
If you don't have a camera attached to the Game Object, of course it won't work. "camera" is just a shortcut for GetComponent(Camera), not GetComponentInChildren(Camera). Just add this at the top of the script and drag your camera's Game Object onto it.
var theCamera : Camera;
Then, change your trouble line to
mousePosition = theCamera.ScreenToWorldPoint(mousePosition);
Call it whatever you like if you don't like "theCamera". I like using C# better for this, because you can still call it "camera", you just need to use
new public Camera camera;
Exactly what I was missing. Stupid mistake. Thanks for the quick answer.
Your answer
Follow this Question
Related Questions
How to prevent GameObject from spawning on top of each other? 1 Answer
Draw a Ray to the Mouse Postion 1 Answer
Can I fake the mouse/touch position relative to the real mouse/touch position? 0 Answers
rotating to mouse location 1 Answer
How to translate Event.current.delta to world position? 0 Answers