- Home /
Add force when button is pressed
I want to make my cube move right when u press button until you release it. When I press button called RightButton nothing happens.
public Rigidbody rb;
public float forwardForce = 2000f;
public float sideForce = 200f;
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetButton("RightButton"))
{
rb.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
Here's screen shot of this button:
I'm new user of unity so don't flame if i'm doing something wrong
the "Button" you added that was not from the UI menu
then you say when pressed you increase the speed
public void Addforce()
{
rb.AddForce(sideForce * Time.deltaTime, 0, 0, Force$$anonymous$$ode.VelocityChange);
}
hope this helped
Answer by Power_Maker · Jan 28, 2018 at 08:50 PM
HEEL YEA I FOUND A SOLUTION. Here's the code:
bool moveRight;
public Rigidbody rb;
public float forwardForce = 2000f;
public float sideForce = 200f;
// Update is called once per frame
void FixedUpdate()
{
// Adding force to player
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (moveRight == true)
{
rb.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
} else
{
rb.AddForce(0, 0, 0, 0);
}
}
public void onPress()
{
moveRight = true;
}
public void onRelease()
{
moveRight = false;
}
Answer by Power_Maker · Jan 27, 2018 at 09:43 AM
@jman12EX I did what u said, but there's one problem it adds force only once when I click, but I want it to add force every "Time.deltaTime".
public Rigidbody rb;
public float forwardForce = 2000f;
public float sideForce = 200f;
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
}
public void Addforce()
{
rb.AddForce(sideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
Now button was added from UI-Button Am I doing something wrong again?
Or meaby I should do this as before but add this button to Edit-Project Settings-Input ?
so sorry i miss under stood this will work
public Rigidbody rb;
public float forwardForce = 2000f;
public float sideForce = 200f;
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
}
public void onPress() //when press you move
{
rb.AddForce(sideForce * Time.deltaTime, 0, 0, Force$$anonymous$$ode.VelocityChange);
}
public void onRelease() //when not press you stop moving
{
rb.AddForce(0, 0, 0, 0);
}
}
to do this you use an event trigger (sorry the image is not uploading i will try to explain)
on the button you add and new component by pressing "Add Component" and look for the "Event Trigger" then you press "Add New Event Type" you will need to add "Pointer Up" and Pointer Down" and pointer up is when it is pressed
It's same as before, adds force only once when I click. I think I need to put some commands to fixUpdate() or make some kind of loop. And I said it wrongly I want to move cube "every frame * Time.deltaTime"
Or meaby there is some method to make button repeat it's function every frame?