- Home /
Physics2D AddForce problems
I'm using AddForce to move my player, and when I run it in the editor, it works great. However, if I build and run it, the forces added seem to be less than when playing in the editor, meaning the player moves a lot slower. It is even worse when running in editor with the animator tab open(much slower than in a build). I have no idea why this is, and cannot seem to figure it out. The script I'm using is below. Thanks for any help!
using UnityEngine;
using System.Collections;
public class PlayerMove : MonoBehaviour
{
public float moveSpeed = 1f;
public float jumpHeight = 3f;
public float thrusterPower = 1f;
public Transform lineStart, lineEnd;
public bool isGrounded;
public bool thrusterEnabled;
void Update ()
{
if(Input.GetKey(KeyCode.D))
{
rigidbody2D.AddForce(Vector2.right * moveSpeed);
}
if(Input.GetKey(KeyCode.A))
{
rigidbody2D.AddForce(-Vector2.right * moveSpeed);
}
if(Input.GetKey(KeyCode.Space))
{
rigidbody2D.AddForce (Vector2.up * thrusterPower);
thrusterEnabled = true;
}
else
{
thrusterEnabled = false;
}
if(Physics2D.Linecast(lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer("Floor")))
{
isGrounded = true;
}
else
{
isGrounded = false;
}
if(isGrounded == true)
{
if(Input.GetKeyDown(KeyCode.W))
{
rigidbody2D.AddForce (Vector2.up * jumpHeight * 100);
}
}
}
}
Also, I have a very powerful computer and checked the processes panel and i was only running at 12% memory and 30% CPU.
Answer by Eric5h5 · Oct 13, 2014 at 09:56 PM
Your code is framerate-dependent since you are using Update, which runs once every frame and has no fixed rate. Physics should only be done in FixedUpdate. (But note that GetKeyDown should not be used in FixedUpdate, since GetKeyDown is only true for the single frame when the key is pressed, which does not necessarily coincide with a FixedUpdate frame.)
Thank you for such a quick reply. So how would I go about rewriting the code without using the update function, because Get$$anonymous$$eyDown seems to be the only way to get a continuous force acting upon the player?
Get$$anonymous$$eyDown is a one-off; Get$$anonymous$$ey is continuous. You can put Get$$anonymous$$ey in FixedUpdate, and use Get$$anonymous$$eyDown in Update to trigger a bool which is checked in FixedUpdate.
Yeah, haha I don't know what I was thinking when I commented, I mixed up Get$$anonymous$$eyDown with Get$$anonymous$$ey. Thank you very much.
Your answer
Follow this Question
Related Questions
Need help with my movement script.. :( 1 Answer
Is there a standardized way for creating a 2D ball physics movement method? 0 Answers
Moving a non-player object in a random direction which bounces off other objects. 2 Answers
2D Smooth movement and collision detection problem 0 Answers
Translate to a target goal position and facing direction and stop 0 Answers