- Home /
Trying to launch a rigidbody towards mouseposition but nothing makes it work.
I'm making a 2d platformer where you can launch yourself towards the place where the player clicks. I'm new to unity and none of the answered questions here seem to solve my problem. I'm using a rigidbody and the part of the script that won't work is as follows: void FixedUpdate () { float move = Input.GetAxis("Horizontal");
body.velocity = new Vector2(move * maxSpeed, body.velocity.y); //basic player movement
if (Input.GetMouseButtonDown(0)){
mousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
direction = (mousePos - body.position);
}
if (Input.GetMouseButtonUp(0))
{
direction.Normalize();
body.AddForce(direction * jumpForce);
}
For some reason the AddForce function does nothing to the player and I'm just clueless at the moment. Using other people's code won't work either because I've tried A LOT.
Answer by Naphier · Oct 14, 2016 at 05:17 PM
Have you debugged the code? What is the values for direction? What is the value of jump force? Also, try ForceMode.Impulse as the second parameter of AddForce.
EDIT: Second issue was that the script above is modifying the rigidbody's velocity directly. This will cause the physics engine to require a recalculation and skip a few frames and can result in bad behavior. Rigidbodies should be moved by AddForce or one of the methods in the Rigidbody class.
Force$$anonymous$$ode.Impulse didn't seem to do anything and I have debugged the code. I noticed that when I set my jumpforce to 1000 my character jumps to the right and then up very fast no matter where I click. $$anonymous$$y direction values seem to be around (0.90, 0.30) most of the time.
In 99% of the cases, Force$$anonymous$$ode.Impulse is what you want to use with any jump-like motion. Otherwise you're over-applying force. Your mouse position needs to be converted from screen coordinates to world coordinates and it does need a z component for that. This answer will help with that http://answers.unity3d.com/questions/540888/converting-mouse-position-to-world-stationary-came.html
Alright thanks a lot that did help and I understand why it does, the only issue I have now is that it doesn't want to move the rigidbody over the X-axis properly. It goes up and down very smoothly but when I want it to move left or right it just teleports to the left or right depending on my jump force.
@Dyonalex - yeah, Unity tutorials unfortunately don't always use the correct methods or are outdated and the API has changed. It's a good idea to make a habit of looking up stuff in the documentation. Please accept my connect as the answer. Thanks
Your answer
Follow this Question
Related Questions
RigidBody2D projectile to target calculation 1 Answer
Move an object via Rigidbody2D Physics and Transform at same time 0 Answers
Unity 2D addforce problem 1 Answer
Rigidbody2D Force Problem 1 Answer