Question by
DiscoHenke · Apr 15, 2016 at 04:40 AM ·
script.timekey pressed
Stop velocity on Keydown for certain time
Hey all,
How can I stop my rigidbody's velocity for 10 seconds after pressing down on E?
if (Input.GetKeyDown(KeyCode.E))
{
//LAST 10 SECONDS
rb.velocity = Vector2.zero;
}
Comment
Answer by Ali-hatem · Apr 15, 2016 at 10:37 AM
if (Input.GetKeyDown(KeyCode.E))
{
rb.velocity = Vector2.zero;
StartCoroutine(Normal());
}
IEnumerator Normal(){
yield return new WaitForSeconds(10f);
rb.velocity = // normal velocity
}
So I already have an IEnumerator called update path:
IEnumerator UpdatePath()
{
//start a new path to the target position (player) from transform position (current position), and return result to the OnPathComplete method;
seeker.StartPath(transform.position, target.position, OnPathComplete);
yield return new WaitForSeconds(1f / updateRate);
StartCoroutine(UpdatePath());
}
and where I am attempting to use keydown I am adding force to the velocity based on certain parameters:
public Force$$anonymous$$ode2D f$$anonymous$$ode;
Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
//$$anonymous$$ove AI in direction
rb.AddForce(dir, f$$anonymous$$ode);
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E))
{
rb.velocity = Vector2.zero;
}
float dist = Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]);
//if close enough to next waypoint, follow waypoint
if (dist < nextWaypointDistance) {
currentWaypoint++;
return;
}
you are using StartCoroutine(UpdatePath());
inside IEnumerator UpdatePath()
you should use it in if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E))
:
void Update(){
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E))
{
rb.velocity = Vector2.zero;
StartCoroutine(UpdatePath());
}
}
IEnumerator UpdatePath()
{
yield return new WaitForSeconds(1f / updateRate);
seeker.StartPath(transform.position, target.position, OnPathComplete);
// move your object
}