- Home /
rigidbody2D Addforce Problem
Hello,
I am currently stuck. I wanted to create a thruster effect with two forces applied to an object. I have two empty gameobjects attached as a child on the bottom right and left side of the parent (the player). When I press 'a' the wrong (right) side goes up, pressing 'd' does nothing most of the time. I am confused.
If someone can help me out, I'd appreciate it. Thanks.
Here is the script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class movement : MonoBehaviour
{
public float speed = 20f;
public int startingEnergy = 100;
private float currentEnergy;
public float energyFill = 10f;
public float energyConsumption = 40f;
public Slider energySlider;
public GameObject leftThruster;
public GameObject rightThruster;
void Awake()
{
currentEnergy = startingEnergy;
}
void FixedUpdate ()
{
if (Input.GetKey ("d") && currentEnergy >= 0f)
{
rigidbody2D.AddForceAtPosition(rightThruster.transform.position, transform.up * speed);
currentEnergy -= energyConsumption * Time.deltaTime;
energySlider.value = currentEnergy;
}
else if (Input.GetKey ("a") && currentEnergy >= 0f)
{
rigidbody2D.AddForceAtPosition(leftThruster.transform.position, transform.up * speed);
currentEnergy -= energyConsumption * Time.deltaTime;
energySlider.value = currentEnergy;
}
else
{
if(currentEnergy <= 100f)
{
currentEnergy += energyFill * Time.deltaTime;
energySlider.value = currentEnergy;
}
}
}
}
Answer by daneislazy · Feb 08, 2015 at 06:29 PM
Always check the documentation!
The force and position vectors are the other way around: http://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForceAtPosition.html
public void AddForceAtPosition(Vector2 force, Vector2 position, ForceMode2D mode = ForceMode2D.Force);
Your answer
Follow this Question
Related Questions
Add force once when object is created 1 Answer
Rigidbody2D AddForce only working with large numbers 2 Answers
Jump problem 1 Answer
Unity 2D Physics .AddForce 1 Answer