Last active
May 29, 2021 15:46
-
-
Save silver-hornet/6b1d8d570bea0958b6a6f1aa9c38eeed to your computer and use it in GitHub Desktop.
2D Moving Object (with RigidBody2D)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add this script to any 2D object you would like to have move automatically once it has been spawned from a different script. | |
// If you're spawning this game object from another script, you'll want this game object to be a prefab. | |
// Ensure you have added a RigidBody2D component in the Inspector and have set its Body Type to Kinematic. | |
// Add the relevant 2D collider (such as a a Box Collider 2D) in the Inspector. | |
using UnityEngine; | |
public class MovingObject : MonoBehaviour | |
{ | |
[SerializeField] Rigidbody2D rb; | |
[SerializeField] float minSpeed = 8f; | |
[SerializeField] float maxSpeed = 12f; | |
float speed; | |
void Start() | |
{ | |
speed = Random.Range(minSpeed, maxSpeed); | |
} | |
void FixedUpdate() | |
{ | |
Vector2 forward = new Vector2(transform.right.x, transform.right.y); | |
rb.MovePosition(rb.position + forward * Time.fixedDeltaTime * speed); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment