简体   繁体   English

在Java Applet中沿随机方向移动对象

[英]Move object in random direction in a Java Applet

I'm trying to create an applet in which the user gets a sheep into a pen by moving a dog towards the sheep and making the sheep move away from the dog in a random direction. 我正在尝试创建一个小程序,在该小程序中,用户通过将狗移向绵羊并使绵羊沿随机方向远离狗而将绵羊放进笔中。 The sheep and dog are defined as objects. 绵羊和狗被定义为对象。

The applet is still in its very early stages. 小程序仍处于早期阶段。 So far I can drag the dog object around the screen and when the dog object comes close to the sheep object it moves but only within a certain area (within bounds I have set). 到目前为止,我可以在屏幕上拖动狗对象,并且当狗对象靠近绵羊对象时,它仅在特定区域内移动(在我设置的范围内)。 I'm not looking for the solution I'm just looking for some help. 我不是在寻找解决方案,而是在寻求帮助。

What I would like help with is making the sheep object move in a random direction away from the dog when the dog object comes within the bounds I have set and not just move within the set bounds. 我需要帮助的是,当狗对象进入我设定的范围内时,使绵羊对象沿随机方向远离狗移动,而不仅仅是在设定范围内移动。 Any help or tips would be greatly appreciated. 任何帮助或技巧将不胜感激。 Here is my code: 这是我的代码:

    package mandAndDog;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;


public class SheepDog extends Applet implements ActionListener, MouseListener, MouseMotionListener
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    /**
     * 
     */

    Dog dog;
    Sheep sheep;
    int xposR;
    int yposR;
    int sheepx;
    int sheepy;
    int sheepBoundsx;
    int sheepBoundsy;

    public void init()
    {
        addMouseListener(this);
        addMouseMotionListener(this);
        dog = new Dog(10, 10);
        sheep = new Sheep(200, 100);
        sheepx = 175;
        sheepy = 75;
        sheepBoundsx = 50;
        sheepBoundsy = 50;


    }
    public void paint(Graphics g)
    {
        dog.display(g);
        sheep.display(g);

    }
    public void actionPerformed(ActionEvent ev)
    {}
    public void mousePressed(MouseEvent e)
    {}
    public void mouseReleased(MouseEvent e)
    {}
    public void mouseEntered(MouseEvent e)
    {}
    public void mouseExited(MouseEvent e)
    {}
    public void mouseMoved(MouseEvent e)
    {
    }
    public void mouseClicked(MouseEvent e)
    {}
    public void mouseDragged(MouseEvent e)
    {
        dog.setLocation(xposR, yposR);
        if (xposR > sheepx&& xposR < sheepx+sheepBoundsx && yposR > sheepy
                && yposR < sheepy+sheepBoundsy){
            sheep.setLocation(xposR + 50, yposR + 50);
        }

        xposR = e.getX();
        yposR = e.getY();
        repaint();

    }
}

class Dog 
{
    int xpos;
    int ypos;
    int circleWidth = 30;
    int circleHeight = 30;

    public Dog(int x, int y)
    {
        xpos = x;
        ypos = y;

    }

    public void setLocation(int lx, int ly)
    {
        xpos = lx;
        ypos = ly;
    }

    public void display(Graphics g)
    {
        g.setColor(Color.blue);
        g.fillOval(xpos, ypos, circleWidth, circleHeight);
    }       
}
class Sheep
{
    int xpos;
    int ypos;
    int circleWidth = 10;
    int circleHeight = 10;

    public Sheep(int x, int y)
    {
        xpos = x;
        ypos = y;

    }

    public void setLocation(int lx, int ly)
    {
        xpos = lx;
        ypos = ly;
    }

    public void display(Graphics g)
    {
        g.setColor(Color.green);
        g.fillOval(xpos , ypos, circleWidth, circleHeight);
    }


}

You aren't looking for code, so here is what what I would do. 您不是在寻找代码,所以这就是我要做的。 This is very basic, and could yield predicable results due to the randomness of the JVM however, I like to use the built-in Math.random() function to generate a random number and the modulus operator to bound the random number to some integer value between 0 and an upper bound. 这是非常基本的,并且由于JVM的随机性可能会产生可预测的结果,但是,我喜欢使用内置的Math.random()函数生成随机数,并使用模运算符将随机数绑定到某个整数介于0和上限之间的值。

I would recommend calculating the direction and distance of travel as a vector. 我建议将旅行的方向和距离计算为向量。

  int MAX_DISTANCE = 50;
  int direction = (int) (Math.random() * 360) % 360;
  int distance = (int) (Math.random() * MAX_DISTANCE) % MAX_DISTANCE;

Here distance is a measure of pixels, and direction is a measure of the angle of travel in degrees. 距离是像素的度量,方向是行进角度的度量,以度为单位。

since we are working in vectors, we can calculate the new pixel location using the angle and distance, and some very basic trig. 由于我们正在处理矢量,因此我们可以使用角度和距离以及一些非常基本的触发来计算新像素的位置。

I would suggest putting this into a function to calculate the new target location, this way, the function can calculate the new location, and if that location is too close to the dog, you can decide on a new path. 我建议将其放入函数中以计算新的目标位置,这样,函数可以计算新的位置,如果该位置离狗太近,则可以决定一条新路径。

If I can make a suggestion, I suggest putting the sheep class into a Timer class that recalculates the sheep's next movement. 如果可以提出建议,建议将绵羊类放到一个Timer类中,以重新计算绵羊的下一个动作。 In this way, the sheep can wander around. 这样,绵羊就可以四处游荡。 While wandering, the sheep might have a much smaller MAX_DISTANCE for each movement. 徘徊时,绵羊的每次移动都可能具有较小的MAX_DISTANCE。 Thereby simulating a level of threat. 从而模拟威胁级别。

If you really want to get into the simulation, you might measure the distance of the dog to the sheep, and based on the distance, scale the speed of the sheeps movements, so that the closer the dog gets, the fast the sheep moves (not to exceed a maximum distance). 如果您真的想进行仿真,则可以测量狗到绵羊的距离,并根据该距离缩放绵羊移动的速度,以便狗越近,绵羊移动得越快(不超过最大距离)。 If you do this, I would recommend you consider using Math.log() to scale the movements so that a 10 pixel reduction in distance from dog to sheep has a smaller effect on the sheep's movement when the dog is 200 pixels away than when the dog is 15 pixels away. 如果这样做,我建议您考虑使用Math.log()缩放运动,以使从狗到绵羊的距离减少10个像素对狗的运动的影响比在距离狗200个像素的情况下小。狗是15像素远。

hope this helps. 希望这可以帮助。

Have a look at the Random class in the Java standard library as it may be of some help. 看一下Java标准库中的Random类,因为它可能有所帮助。 You could easily generate pseudo-random ints and adjust the (x,y) of your characters. 您可以轻松生成伪随机整数并调整字符的(x,y)。 Add some error-checking to make sure they move away from each other and you should be good to go! 添加一些错误检查,以确保它们彼此远离,您应该一切顺利!

I would divide the directions you want to move the sheep into a number. 我会将您要移动的方向分为几个数字。 If the sheep can move up, down, left, and right, and you subtract a direction that the wolf comes from, say left you are left with three. 如果绵羊可以向上,向下,向左和向右移动,并且您减去了狼的方向,那么说左手剩下三个。 Up down and right. 上下左右。

Use Math random function to pick a random one of these, you can look in the API but basically multiply by the max number you want random and cast as an Int to get rid of the decimals. 使用Math随机函数从这些函数中选择一个随机数,您可以在API中查找,但基本上要乘以您想要随机数的最大值,然后将其强制转换为Int以去除小数。

int intDirection = (int)(Math.random()*3);  

this will give should give you either 0, 1 and 2. Then make a case statement to move the direction based off the number. 这将给您0、1和2。然后执行一个case语句以根据数字移动方向。 Maybe for good practice look into enumerators for the three directions . 也许为了更好的实践,研究了三个方向的枚举器。

If you wanted to have more directions you could look into vectors, this is how you do random however. 如果您想了解更多方向,可以研究矢量,但是这是随机的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM