- Home /
More information about the problem was discovered and I posted another question that explains the problem better.
Sprite moving too far/fast
I feel kind of stupid even asking this question because it seems like it should be a relatively simple thing to figure out, but I've spent a few days trying to figure it out and can't do it. I just need to move a sprite from one side of the screen to the other. This is the basic line of code I used.
transform.position += direction * speed * Time.deltaTime;
In this scenario the direction is (-1,0,0), the speed is 5 and the code is in void Update. However when run the sprite instantaneously moves to the edge of the screen where I constrained its movement to. Debug.Logs show that it is simply moving insanely fast, reaching the edge of the screen within less than a second. I've tried lowering the speed, using Vector3.Lerp, and using other methods such as transform.Translate, but it always just moves straight to its maximum distance in less than a second. This is my first 2D project, so I could be going about it the wrong way or I'm just overlooking something simple. Either way I'm not sure what to do and have wasted enough time trying to figure it out myself, so if anyone can help me out I'd really appreciate it.
Answer by michaelfelleisen · Jun 30, 2020 at 06:43 AM
you can try to use:
transform.Translate(direction * speed * Time.deltaTime);
but it seems like your mistake is somewhere else in your script! can you post the rest of your script?
private float speed = 1.0f;
private GameObject database;
private Vector3 direction;
private float north;
private float east;
private float south;
private float west;
public bool alive = true;
// Start is called before the first frame update
void Start()
{
database = GameObject.Find("DataBase");
if (database == null )
{
Debug.Log("DataBase not Found");
}
data dat = database.GetComponent<data>();
direction = dat.direct;
north = dat.NW.y;
west = dat.NW.x;
south = dat.S$$anonymous$$y;
east = dat.S$$anonymous$$x;
}
void Update()
{
while (alive)
{
transform.position += direction * speed * Time.deltaTime;
if (transform.position.x <= west || transform.position.x >= east)
{
alive = false;
}
if (transform.position.y >= north || transform.position.y <= south)
{
alive = false;
}
Debug.Log("Transform Position: " + transform.position);
}
}
This is pretty much it. The north south east and west are just the values which correspond to the edge of the screen.
Follow this Question
Related Questions
Move with Rigidbody2D in the Z axis 3 Answers
Dash in the direction of a parents child object 1 Answer
How can I rotate my player to look at the direction my Joystick is pointing to? (Top-Down 2D) 3 Answers
How can i fix a position of a gameobject after it meets its condition 1 Answer
How can i execute a code when a trigger enter is called 0 Answers