- Home /
Question by
akashisayaki · Feb 03, 2021 at 05:07 PM ·
unity 2dforcegame developmentobstacle
Constantly add force and throw an object in every 2 seconds!
Hi, I want to know if there's any methods to add force and throw an object without using any buttons but with seconds? Every 2 seconds the ball will add force and launch itself towards the player. I want to make it as an obstacle for my game. This is the code for now: public class EnemyBouncer : MonoBehaviour {
public float speed;
public float stoppingDistance;
public float retreatDistance;
public Transform player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
if (Vector2.Distance(transform.position, player.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
}
else if (Vector2.Distance(transform.position, player.position) < stoppingDistance && Vector2.Distance(transform.position, player.position) > retreatDistance)
{
transform.position = this.transform.position;
}
else if ((Vector2.Distance(transform.position, player.position) < retreatDistance))
{
transform.position = Vector2.MoveTowards(transform.position, player.position, -speed * Time.deltaTime);
}
}
}
Comment
Answer by Llama_w_2Ls · Feb 03, 2021 at 06:48 PM
You can use a coroutine to do this. For example:
void Start()
{
StartCoroutine(FireObject(2));
}
IEnumerator FireObject(float delay)
{
// Waits 'delay' amount of seconds
yield return new WaitForSeconds(delay);
// Fires object
Fire();
}
Answer by afraism · Feb 03, 2021 at 07:05 PM
This can be done with InvokeRepeating
using UnityEngine;
using System.Collections.Generic;
// Starting in 2 seconds.
// a projectile will be launched every 0.3 seconds
public class ExampleScript : MonoBehaviour
{
public Rigidbody projectile;
void Start()
{
InvokeRepeating("LaunchProjectile", 2.0f, 0.3f);
}
void LaunchProjectile()
{
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5;
}
}
public void InvokeRepeating(string methodName, float time, float repeatRate);