Quantcast
Channel: Questions in topic: "addforce"
Viewing all articles
Browse latest Browse all 1264

AddForce Impulse not moving the object

$
0
0
Hi, I have a prefab object called "Meteor", which is instantiated randomly at the right edge of the screen using a coroutine. The meteor is instantiated through another script, named "meteorController", to prevent clones from instantiating themselves. The script is attached to a gameobject with the same name. After MeteorPrefab is instantiated, I want to give it force towards another object, called "Spaceship". I've tried doing it using AddForce with Impulse as the force mode, but it's not working: the meteors are instantiated properly but they aren't moving at all, although no error messages are displayed. The MeteorPrefab's rigidbody is set to "dynamic" and it has a mass value of 1. I'm new to #c. maybe something is wrong with my code? Help would be appreciated. Thanks The meteorController script: using System.Collections; using System.Collections.Generic; using UnityEngine; public class meteorController : MonoBehaviour { public GameObject MeteorPrefab; public float timer = 5.0f; private Vector2 screenBounds; public Transform spaceship; public Rigidbody2D rb; public float force = 100.0f; void Start() { screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z)); StartCoroutine(Meteor()); Debug.Log(screenBounds); } private void SpawnMeteor() { GameObject spawn = Instantiate(MeteorPrefab) as GameObject; spawn.transform.position = new Vector2(screenBounds.x, Random.Range(-screenBounds.y, screenBounds.y)); rb = spawn.GetComponent(); Vector3 direction = spaceship.position - transform.position; float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; rb.rotation = angle; rb.AddForce(spawn.transform.forward * force, ForceMode2D.Impulse); } IEnumerator Meteor() { while (true) { yield return new WaitForSeconds(timer); SpawnMeteor(); } } } Here's a screenshot of the MeteorPrefab's Rigidbody2D component: ![alt text][1] [1]: /storage/temp/192470-screenshot-2022-02-11-102405.png

Viewing all articles
Browse latest Browse all 1264

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>