- Home /
Question by
PersianKiller · Jul 24, 2017 at 06:03 AM ·
updatefunctionfixedupdateif statementinput.getkey
Can use FixedUpdate in Update?
Hi, it's my code
void Update () {
if (Input.GetKey (KeyCode.J)) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (5,0);
}
}
but the problem is that we should get inputs in Update and use all object that have Rigidbody2D in FixedUpdate
how can I get input in Update and then use RigidBody2D to move the object in FixedUpdate?
???
Comment
Best Answer
Answer by Kishotta · Jul 24, 2017 at 06:13 AM
You can use a class level variable to separate your concerns. Also you should cache your Rigidbody2D for performance:
Vector2 force;
Rigidbody2D rb2d;
void Awake () {
rb2d = GetComponent<Rigidbody2D> ();
}
void Update () {
if (Input.GetKey (KeyCode.J)) {
force = new Vector2 (5, 0);
} else {
force = Vector2.zero;
}
}
void FixedUpdate () {
rb2d.velocity = force;
}
Your answer
Follow this Question
Related Questions
What's FixedUpdate 2 Answers
Rigidbody.AddForceAtPosition & functions 1 Answer
Input.GetKey missing keyboard state on Update and FixedUpdate 2 Answers
Help with If statement INSIDE if statement!! 2 Answers
Jumping randomly doesn't work 2 Answers