Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to make a 2D object move with constant speed

Discussion in 'Scripting' started by Bazoozoo, Aug 22, 2015.

  1. Bazoozoo

    Bazoozoo

    Joined:
    Mar 27, 2015
    Posts:
    28
    I'm new to unity and wanted to know how to make a sprite move with a constant speed.
     
  2. Duugu

    Duugu

    Joined:
    May 23, 2015
    Posts:
    241
    That depends on the type of you object and other stuff.
    Does the object have a rigidbody component attached? > AddForce(), etc.
    No rigidbody? > update the objects position via transform
     
  3. Bazoozoo

    Bazoozoo

    Joined:
    Mar 27, 2015
    Posts:
    28
    I'm trying to do it without a rigidbody2D component. I want the sprite to bounce off colliders without losing speed as well. I think you reverse the velocity or something?
     
  4. Duugu

    Duugu

    Joined:
    May 23, 2015
    Posts:
    241
    Velocity is a rigidbody attribute.

    Could you please show your actual code to have something to start with? Thanks!
     
  5. Bazoozoo

    Bazoozoo

    Joined:
    Mar 27, 2015
    Posts:
    28
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Speed : MonoBehaviour {
    5.  
    6.     public float speed = 2.0f;  
    7.    
    8.     void Update () {
    9.  
    10.         transform.position += transform.right * speed * Time.deltaTime;
    11.    
    12.     }
    13. }
    14.  
    How can I set the original direction of the of the moving object? Is it through Vector2?
     
  6. Duugu

    Duugu

    Joined:
    May 23, 2015
    Posts:
    241
    Hm I am not sure if I do get you right, sorry. Moving into the opposite direction would be:
    Code (CSharp):
    1. transform.position += -transform.right * speed * Time.deltaTime;
     
    GamestuffAndCo likes this.
  7. bjohnsonco08

    bjohnsonco08

    Joined:
    May 3, 2020
    Posts:
    1
    Cool! It worked with my enemy script!