Skip to content

Instantly share code, notes, and snippets.

@silver-hornet
Last active May 29, 2021 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silver-hornet/6b1d8d570bea0958b6a6f1aa9c38eeed to your computer and use it in GitHub Desktop.
Save silver-hornet/6b1d8d570bea0958b6a6f1aa9c38eeed to your computer and use it in GitHub Desktop.
2D Moving Object (with RigidBody2D)
// 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