- Home /
How to throw a rigidbody toward the mouse?
Hi,
I'm trying to make a game, but I'm quite new to Unity and to programming. I recently got a problem with a feature of my game.
I'm making 2.5D sidescroller and I'm actually trying to create a script which will allow my character to throw a sphere in the direction of the mouse cursor, but for an unknown reason my sphere almost only move in the y axis. It slides a little bit on the x axis but no more.
Also, my sphere only move the the right, not on the left. If someone could help me on that, that would be greetly appreciated.
Here's my code:
using UnityEngine;
using System.Collections;
public class Spherecontroller : MonoBehaviour {
public Rigidbody Srigid;
public float throwforce;
private Vector3 Mposition;
public Camera gamecamera;
private Vector3 throwvector;
void Start() {
Mposition = gamecamera.ScreenToWorldPoint(Input.mousePosition);
throwvector = new Vector3 (Mposition.x * throwforce, Mposition.y * throwforce);
}
void FixedUpdate () {
Srigid = GetComponent<Rigidbody> ();
if (Input.GetMouseButtonDown (0)) {
Srigid.AddForce (throwvector);
}
}
}
Answer by robertbu · Oct 16, 2014 at 04:13 AM
One problem is that you only calculate MPosition in Start(). You need to calculate it just before you add force. In addition, GetMouseButtonDown() should not be called in FixedUpdate() and there is no reason to call a one-time AddForce() in FixedUpdate().
Thanks for the help but I found the problem.
It was caused by the Input.mousPosition. By default the z axis is set at 0, which is the distance of the pointer from the camera. It caused the engine to always use the camera position as the mouse position.
I simply had to create a varaible for the distance between my scene and the camera and put it in the z axis.
Your answer
Follow this Question
Related Questions
How do I determine mouse speed on the x and z axis? 0 Answers
Cant unlock cursor with FPS prefab 2 Answers
Cursor lock not working after alt tab 2 Answers
Lock mouse position with a Rect, possible? 1 Answer
Cursor out of range 0 Answers