So I created a monster which I want to be consistently moving right and left between x= 156 and x = 501 Here's what i have done so far in my move() method:
public void move()
{
int left = 156;
int right = 501;
if (left <= x)
{
x++;
}
if (x >= 501)
{
x -= 1;
}
}
Then I call the method using a timer
private void tmr2_Tick(object sender, EventArgs e)
{
foreach (Monster m in monsters_)
{
m.move();
}
screen.Refresh();
}
This doesn't work. Could someone please help out. Thanks
Beside coordinates X and Y the monster has to have one more property, let's call it Direction. When monster reaches one of the goals you change this Direction property, and only then you adjust the coordinates.
This might do the work for you
public class Monster
{
private const int MIN_X = 156;
private const int MAX_X = 501;
private int _x;
//your TL(probably) will tell you to use Enum
private bool _toLeft;
public Monster()
{
_toLeft = false;
_x = MIN_X;
}
public void Move()
{
if (_toLeft)
{
_x--;
}
else
{
_x++;
}
CheckEdges();
}
private void CheckEdges()
{
if (_x == MAX_X || _x == MIN_X)
_toLeft = !_toLeft;
}
}
You are missing the notion of direction in your code. You can do it in hundreds of ways so I'm not going to write the code here.
But once your x is equal to 501, you are decreasing its value by one, so on the next call its value is 500 therefore resetting it to 501 and so on. This is why it stops moving. You need to change direction on the edges, therefore increase or decrease X until you hit the other edge.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.