Basic 2D script

Hi, I’m new to Unity.
I’ve been trying to learn little by little and almost always found what I was searching for on the internet, but not this time… I’m working on a mini 2D game, and in some scene, I need an object to fall from the sky at a slow constant speed, I don’t want this velocity to ever change.
The problem is that I need my player to stand on this Object, and therefore I need this player to move at the same speed of this object, but adding RigidBody2D to the object allows my player to “push it down” and thus changing its velocity.
It’s a very basic code yet I cannot seem to figure it out, I would love it if somebody would provide 2-3 simple lines of code explaing how to do this too.
Thanks in advance!

1 Like

I hope I got this right. I implemented a similar logic for falling objects in my game. Here’s how I did it:

    void Update()
    {
        transform.position -= new Vector3(0, fallSpeed * Time.deltaTime, 0);
    }

In this case, you don’t need a Rigidbody
Attach this script to your object and set the value for fallSpeed

Thank you for replying.
I tried this, for some reason the Object stays still and doesn’t move at all, do you have any idea why this problem might occur?

Could you provide a screenshot of the object and it`s inspector and the full script that you attached to it?

Here is the script attached to the object, in the object spawner I called for SpawnGround(8,8) just to test the code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FloatingGroundBehaviour : MonoBehaviour
{
    [SerializeField] public GameObject prefab;
    [SerializeField] float SpawnHeight;
    [SerializeField] float SpawnWidthRange;
    [SerializeField] public float dropVel;

    void update()
    {
        transform.position -= new Vector3(0f, dropVel, 0f);
    }

   public void SpawnGround() 
    {
        Instantiate(prefab, new Vector3(Random.Range(-SpawnWidthRange, SpawnWidthRange), SpawnHeight, 0f), Quaternion.identity);
    }

    public void SpawnGround(float x, float y)
    {
        Instantiate(prefab, new Vector3(x, y, 0f), Quaternion.identity);
    }
    

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.tag == "DeathGround")
        {
            SpawnGround();
            Destroy(gameObject);
        }
    }



}

This is a script for an object that is supposed to fall, right?

  1. I’m not sure if Update() works if it’s written in lowercase
  2. You forgot Time.deltaTime

Try this:

    void Update()
    {
        transform.position -= new Vector3(0f, dropVel * Time.deltaTime, 0f);
    }
1 Like

It worked! thank you man!

1 Like