Reputation: 1919
I have a GameObject that I want to move in Unity. I want to move it by a fixed distance. I have tried using AddForce but the game object keeps on moving infinitely.
Here is my code:
Vector2 movementMonster = new Vector2(-4, 0);
rbMonster1.AddForce(movementMonster);
I have also tried Translate without any results:
monster1.transform.Translate(Vector2.left * 5 * Time.deltaTime);
Upvotes: 1
Views: 10546
Reputation: 21
The Transform.Translate(movementMonster) will move your GameObject by the defined Vector3 movement monster every time you call it. Example:
Let's assume that start position of the monster if Vector3(0,0)
monster1.transform.Translate(movementMonster);
After first call your monster is now at Vector3(-4, 0, 0)
monster1.transform.Translate(movementMonster);
After first call your monster is now at Vector3(-8, 0, 0)
monster1.transform.Translate(movementMonster);
Vector3(-12, 0, 0) etc..
As long as I understand you need to move the 'monster' to certain position over time. You can use the method of Vector3.MoveTowards()
so you can skip some math.
using UnityEngine;
class Monster : MonoBehaviour {
public Vector3 endPosition;
public float speed = 1f; // The monster will move a one unity per second
public void Update(){
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, endPosition, step);
}
You may want to hit the Unity3D tutorial page, where this kind of basics are explained. https://unity3d.com/learn/tutorials/s/scripting
Upvotes: 1
Reputation: 10320
.Translate requires a Vector3:
Vector3 movementMonster = new Vector3(-4, 0, 0);
Do you want to move it a fixed distance in a single frame?
monster1.transform.Translate(movementMonster);
or over a certain time (for example a second)?
monster1.transform.Translate(movementMonster * Time.deltaTime);
Upvotes: 1