GPWiki.org
GPWiki.org
It is currently Tue Jun 18, 2013 6:18 am

All times are UTC




Post new topic Reply to topic  [ 11 posts ] 
Author Message
PostPosted: Thu Mar 29, 2012 2:19 am 
hey guys !
hope at least here i will find some guidance to my problem.
i have post my issues already on this website ... nothing no useful answer hope i will find the help i need here..
When it comes to pathfinding A star most of people are blocked in the A star but fortunately me i did find the algorythm from wiki and with my basic knowledge i follow it and made it work so far without of course no blocks ( tiles as wall kind of thing) and of course i red a lot of tutorials and even in my codes i use a class found over the internet...well my problem now even it might not be the best path but at least i got a path so all i want now is how to make my character follow the path which is for now just an image of mario.. i am trying to learn step by step so can you guys please help me guide me with some algorithms or code spinets or any tutorial i must admit it i do understand everything so far except how to make that image follow the path so far what i did it rather he move one time or just go all the way up..this i have no clue how to do it..
so here's my code thank you guys

main

Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;


 public class GameBoard extends JPanel implements ActionListener,Runnable{
 private Thread game;
 private volatile boolean running=false;
 Map m;
 Player hero;
 Path path;
 AstarPathfinder p1;
 int targetX,targetY;
 int dir=0;
 public GameBoard ()
 {
   //setSize(620,720);
   setBackground(Color.gray);
   setFocusable(true);
   requestFocus();
   hero=new Player();
   hero.setX(3/36);
   hero.setY(3/36);

    addMouseListener(new MouseAdapter()
           {
        public void mouseClicked(MouseEvent e) {
            handleMousePressed(e.getX(), e.getY());
        }
    });
    addMouseMotionListener(new MouseMotionListener() {
        public void mouseDragged(MouseEvent e) {
                       // System.out.println("mouse dragged");
        }

        public void mouseMoved(MouseEvent e) {
            //handleMouseMoved(e.getX(), e.getY());
        }
    });

}

private void handleMousePressed(int x, int y)
    {   
    targetX=x /= 36;
    targetY=y/= 36;
            p1=new  AstarPathfinder ();
            path=p1.PathFinding(hero.getX()/36, hero.getY()/36, targetX,targetY);
            repaint();
    }




public void startGame()
{
     if(game==null|| !running)
   {     
               game=new Thread(this);
               game.start();
               running=true;                       


   }   
}
@Override
  public void run()
{
   while(running)
   {

        moveit();

        try {

            Thread.sleep(5);

        } catch (InterruptedException ex) {
            Logger.getLogger(GameBoard.class.getName()).log(Level.SEVERE, null, ex);
        }

   }
}

public void moveit()
{
    for(int x=0; x<14; x++)
    {
        for(int y=0;y<14;y++)
        {

                                     if (path != null)
                                   {

                 if (path.contains(x,y))
                                         {
                                            if(path.getX(x)<hero.getX()){
                                             hero.x-=1;
                                             }
                                             else if(path.getX(x)> hero.getX())
                                             {
                                               hero.x+=1;
                                             }


                                              if(path.getY(y)< hero.getY())
                                              {
                                                hero.y-=1;
                                              }
                                              else  if(path.getY(y)> hero.getY())
                                              {

                                               hero.y+=1;
                                              }


               }
            }
        }
      }

   }
   @Override
   public void paint(Graphics g)
   {
   m=new Map();     
   m.OpenFile();
   m.ReadFile();
   m.CloseFile();

    for(int y=0; y<14; y++)
    {
        for(int x=0; x<14; x++)
       {

           if(m.getMap(x, y).equals("g"))
           {
              g.drawImage(m.getGrass(), x*36, y*36, this);
           }

           if(m.getMap(x, y).equals("b"))
           {
                g.drawImage(m.getBlock(), x*36, y*36, this);
           }
           if(m.getMap(x, y).equals("d"))
           {
                g.drawImage(m.getDirt(), x*36, y*36, this);
           }
           if(m.getMap(x, y).equals("t"))
           {
                g.drawImage(m.getGOAL(), x*36, y*36, this);



           }


                           if (path != null)
                             {

                      if (path.contains(x,y))
                                           {
                                                    g.setColor(Color.YELLOW);
                        g.fillRect(x*36, y*36,19,19);
                                           }

                }


       }
    }

 }
  @Override
  public void addNotify()
  {//build in jpanel method
    super.addNotify();
   ///donc quand le jpanel est en marche partir le jeu.
    startGame();



 }

  @Override
  public void actionPerformed(ActionEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
  }


 }




end my entity class



Code:
public class Entity {

int x, y, dx, dy;

public Entity() {
    x = 0;
    y = 0;
    dx = 0;
    dy = 0;
}

public Entity(int xe, int ye) {
    this.x = xe;
    this.y = ye;
}

public int getDx() {
    return dx;
}

public void setDx(int dx) {
    this.dx = dx;
}

public int getDy() {
    return dy;
}

public void setDy(int dy) {
    this.dy = dy;
}

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

public int getY() {
    return y;
}

public void setY(int y) {
    this.y = y;
}
}




player

Code:
 import java.awt.Graphics;
  import java.awt.Image;
  import javax.swing.ImageIcon;

 public class Player extends Entity {
 private Image p;
public Player()
{
   super();
    p=new ImageIcon("C:/Java/Prj/src/images/player.png").getImage();
}

 public Image getPlayer()
{
    return p;
}
/* public void move(char d)
 {
     if(d=='d')
     this.x+=this.dx;
     this.y+=this.dy;
 }*/
public void drawPlayer(Graphics g)
{

   g.drawImage(this.p,this.x,this.y,null);

}
}



astar class

Code:
 import java.util.ArrayList;
  import java.util.LinkedList;
  import java.util.List;

 public class AstarPathfinder {

LinkedList<Node> closed = new LinkedList();
LinkedList<Node> open = new LinkedList();
int newH, newF, newG, ndlength = 14;
Node[][] nodes = new Node[ndlength][ndlength];
Path path;

public AstarPathfinder() {


    for (int i = 0; i < ndlength; i++) {
        for (int j = 0; j < ndlength; j++) {
            nodes[i][j] = new Node(i, j);
        }
    }

}

public Path PathFinding(int sx, int sy, int tx, int ty) {
    Node start = nodes[sx][sy];
    Node target = nodes[tx][ty];
    start.g = 0;
    start.h = estimateCost(start, target);
    start.f = start.g + start.h;

    start.parent = null;
    open.add(start);



    while (open.size() != 0) {

        Node current = null;

        if (open.size() == 0) {
            System.out.println("aucune route/no possible road");
        }


        current = getCurrent();
        if (current == target) {
            //System.out.println("reach the target: " + target);
            break;
        }
        open.remove(current);
        closed.add(current);




        List<Node> neighbors = (List<Node>) createNeighbors(current);

        for (int k = 0; k < neighbors.size(); k++) {

            Node neighborNode = neighbors.get(k);
            if (closed.contains(neighborNode)) {
                continue;
            }
            newG = current.g + 10;// + estimateDistance(current, neighborNode);
            newH = estimateCost(neighborNode, target);
            newF = newG + newH;

            if (newG < neighborNode.g) {

                neighborNode.parent = current;
                neighborNode.h = newH;
                neighborNode.g = newG;
                neighborNode.f = newF;

            }
            if ((!open.contains(neighborNode)) && !(closed.contains(neighborNode))) {

                open.add(neighborNode);
                neighborNode.parent = current;
                neighborNode.h = newH;
                neighborNode.g = newG;
                neighborNode.f = newF;
            }
        }//endloopfor

    }//end while

    path = new Path();
    Node target2 = target;
    while (target2 != start) {
        path.prependStep(target2.x, target2.y);
        target2 = target2.parent;

    }

    path.prependStep(start.x, start.y);
    return path;
}

public int estimateCost(Node node1, Node node2) {
    float resultat;
    float dx = node1.x - node2.x;
    float dy = node1.y - node2.y;
    resultat = Math.abs((dx * dx) + (dy + dy));
    resultat += resultat * 0.001;
    return (int) resultat;
}

/**
 * cette fonction perment de retourner le noeud courant
 * @return
 */
private Node getCurrent() {
    Node currentNode = null;
    int maxintf = open.size();
    int minf = 1000000;
    for (int i = 0; i < maxintf; i++) {
        Node node = (Node) open.get(i);
        if (node.f < minf) {
            currentNode = node;

        }
    }
    return currentNode;
}

/**
 * Fontion permettant de trouver les 8 voisins
 */
private List<Node> createNeighbors(Node cnodes) {
    int i = cnodes.x;
    int j = cnodes.y;
    List<Node> neighbors = new ArrayList<Node>();
    int indiceup = cnodes.x - 1;
    int indicedown = cnodes.x + 1;
    int indiceleft = cnodes.y - 1;
    int indiceright = cnodes.y + 1;
    if (indiceup > -1) {
        neighbors.add(nodes[indiceup][cnodes.y]);
    }
    if (indicedown < 14) {
        neighbors.add(nodes[indicedown][cnodes.y]);
    }
    if (indiceleft > -1) {
        neighbors.add(nodes[cnodes.x][indiceleft]);
    }
    if (indiceright < 14) {
        neighbors.add(nodes[cnodes.x][indiceright]);
    }
    return neighbors;
}

public class Node {

    int g = 0;//cost
    int h = 0;//heuristic
    int f = g;//f+g
    Node parent;
    int x, y;
    boolean visited;

    public Node(int x, int y) {
        this.x = x;
        this.y = y;
        this.visited = false;
    }

    public boolean isVisited() {
        return visited;
    }

    public void setVisited(boolean visited) {
        this.visited = visited;
    }

    public int getF() {
        return f;
    }

    public void setF(int f) {
        this.f = f;
    }

    public int getG() {
        return g;
    }

    public void setG(int g) {
        this.g = g;
    }

    public int getH() {
        return h;
    }

    public void setH(int h) {
        this.h = h;
    }

    public Node getParent() {
        return parent;
    }

    public void setParent(Node parent) {
        this.parent = parent;
    }
    }
    }


this is the path class found on google...

Code:
  import java.util.ArrayList;

    public class Path {
/** The list of steps building up this path */
private ArrayList steps = new ArrayList();

/**
 * Create an empty path
 */
public Path() {

}

/**
 * Get the length of the path, i.e. the number of steps
 *
 * @return The number of steps in this path
 */
public int getLength() {
    return steps.size();
}

/**
 * Get the step at a given index in the path
 *
 * @param index The index of the step to retrieve. Note this should
 * be >= 0 and < getLength();
 * @return The step information, the position on the map.
 */
public Step getStep(int index) {
    return (Step) steps.get(index);
}

/**
 * Get the x coordinate for the step at the given index
 *
 * @param index The index of the step whose x coordinate should be retrieved
 * @return The x coordinate at the step
 */
public int getX(int index) {
    return getStep(index).x;
}

/**
 * Get the y coordinate for the step at the given index
 *
 * @param index The index of the step whose y coordinate should be retrieved
 * @return The y coordinate at the step
 */
public int getY(int index) {
    return getStep(index).y;
}

/**
 * Append a step to the path. 
 *
 * @param x The x coordinate of the new step
 * @param y The y coordinate of the new step
 */
public void appendStep(int x, int y) {
    steps.add(new Step(x,y));
}

/**
 * Prepend a step to the path. 
 *
 * @param x The x coordinate of the new step
 * @param y The y coordinate of the new step
 */
public void prependStep(int x, int y) {
    steps.add(0, new Step(x, y));
}

/**
 * Check if this path contains the given step
 *
 * @param x The x coordinate of the step to check for
 * @param y The y coordinate of the step to check for
 * @return True if the path contains the given step
 */
public boolean contains(int x, int y) {
    return steps.contains(new Step(x,y));
}

/**
 * A single step within the path
 *
 * @author Kevin Glass
 */
public class Step {
    /** The x coordinate at the given step */
    private int x;
    /** The y coordinate at the given step */
    private int y;

    /**
     * Create a new step
     *
     * @param x The x coordinate of the new step
     * @param y The y coordinate of the new step
     */
    public Step(int x, int y) {
        this.x = x;
        this.y = y;
    }

    /**
     * Get the x coordinate of the new step
     *
     * @return The x coodindate of the new step
     */
    public int getX() {
        return x;
    }

    /**
     * Get the y coordinate of the new step
     *
     * @return The y coodindate of the new step
     */
    public int getY() {
        return y;
    }

    /**
     * @see Object#hashCode()
     */
    public int hashCode() {
        return x*y;
    }

    /**
     * @see Object#equals(Object)
     */
    public boolean equals(Object other) {
        if (other instanceof Step) {
            Step o = (Step) other;

            return (o.x == x) && (o.y == y);
        }

        return false;
    }
}
    }



i have try so many things and find some weird results hope from this you guys could help me with it..
lately i modify my class main to give me this well gameboard still


Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;


 public class GameBoard extends JPanel implements ActionListener,Runnable{
 private Thread game;
 private volatile boolean running=false;
 Map m;
 Player hero;
 Path path;
 AstarPathfinder p1;
 int targetX,targetY;
 int dir=0;
  int index=0;
   int dx,dy,px,py,temp=0;
 public GameBoard ()
 {
   //setSize(620,720);
   setBackground(Color.gray);
   setFocusable(true);
   requestFocus();
   hero=new Player();

     System.out.println("return p:"+ hero.getPlayer());
    addMouseListener(new MouseAdapter()
           {
        public void mouseClicked(MouseEvent e) {
            handleMousePressed(e.getX(), e.getY());
        }
    });
    addMouseMotionListener(new MouseMotionListener() {
        public void mouseDragged(MouseEvent e) {
                       // System.out.println("mouse dragged");
        }

        public void mouseMoved(MouseEvent e) {
            //handleMouseMoved(e.getX(), e.getY());
        }
    });

}

private void handleMousePressed(int x, int y)
    {   
            targetX=x /= 36;
           targetY=y/= 36;
            p1=new  AstarPathfinder ();
            path=p1.PathFinding(hero.getX()/36, hero.getY()/36, targetX,targetY);
            repaint();
    }




public void startGame()
{
     if(game==null|| !running)
   {     
               game=new Thread(this);
               game.start();
               running=true;                       


   }   
}
@Override
  public void run()
{
   while(running)
   {
move();
     repaint();
   

        try {

            Thread.sleep(5);

        } catch (InterruptedException ex) {
            Logger.getLogger(GameBoard.class.getName()).log(Level.SEVERE, null, ex);
        }

   }
}
public void move()
{
   
                           
                       if (path != null)
                             {
                                 
                              px=path.getX(index)*36/36;
                              py=path.getY(index)*36/36;
                             
                              dx=px-hero.getX()/36;
                             
                              dy=py-hero.getY()/36;
                             
                                 System.out.println("==?"+dx +":"+dy);
                                 System.out.println("dx:"+dx +" dy :"+dy);
                                 temp=(int) Math.sqrt(dx*dx +dy *dy );
                               //System.out.println("px:"+ px +""+path.getX(index));
                               //  System.out.println("temp: "+temp);
                                 if(temp<1)
                                 {
                                   index++; 
                                 }
                                 else
                                 {
                                   
                                     if(px < hero.x )
                                     {
                                      hero.x+=1;
                                         System.out.println("left");
                                     }
                                     else if(px > hero.x)
                                     {
                                       hero.x-=1;   
                                               System.out.println("right");
                                     }
                                   
                                     
                                       
                                     if(py < hero.y)
                                     {
                                      hero.y+=1;
                                             System.out.println("down");
                                     }
                                     else if(py > hero.y && hero.y < 620)
                                     {
                                       hero.y-=1;           System.out.println("up");
                                     }
                                 }
                                 
                                 
                                 
                                 
                                 
                                 //   hero.move(x, y);   
                           
                                 
                             }
 
   
}

   @Override
   public void paint(Graphics g)
   {
   m=new Map();     
   m.OpenFile();
   m.ReadFile();
   m.CloseFile();

    for(int y=0; y<14; y++)
    {
        for(int x=0; x<14; x++)
       {
           //  g.drawImage(hero.getPlayer(),hero.getX(),hero.getY(), this);
           if(m.getMap(x, y).equals("g"))
           {
              g.drawImage(m.getGrass(), x*36, y*36, this);
           }

           if(m.getMap(x, y).equals("b"))
           {
                g.drawImage(m.getBlock(), x*36, y*36, this);
           }
           if(m.getMap(x, y).equals("d"))
           {
                g.drawImage(m.getDirt(), x*36, y*36, this);
           }
           if(m.getMap(x, y).equals("t"))
           {
                g.drawImage(m.getGOAL(), x*36, y*36, this);



           }

           g.drawImage(hero.getPlayer(),hero.getX(),hero.getY(), this);
                           if (path != null)
                             {

                                 //System.out.println("idenx:"+ path.getY(y));
                          //  // hero.move(x, y);   
                           
//                         /repaint();
                                   
   
                       
                      if (path.contains(x,y))
                                           {  //System.out.println("id:"+ path.getStep(9));
                        g.setColor(Color.YELLOW);
                        g.fillRect(x*36, y*36,19,19);
                                           }

                }


       }
    }

 }
  @Override
  public void addNotify()
  {//build in jpanel method
    super.addNotify();
   ///donc quand le jpanel est en marche partir le jeu.
    startGame() ;



 }

  @Override
  public void actionPerformed(ActionEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
  }


 }


Top
  
 
PostPosted: Thu Mar 29, 2012 2:27 am 
Rookie

Joined: Thu Mar 29, 2012 2:05 am
Posts: 4
sorry guys i am the one who post this topics.. unfortunately it went 2 times please admin delete one don't want to flood or anything and i register after the post sorry


Top
 Profile  
 
PostPosted: Thu Mar 29, 2012 3:29 pm 
Dexterous Droid
User avatar

Joined: Wed Aug 18, 2004 7:40 pm
Posts: 3745
Location: South Africa
Here's my code for following a path. Unfortunately it's in C++, but I think you can read it and understand the logic to implement your own version in Java. It's probably not the best solution, but it worked for me :)

If you have your path stored as a vector of all the tiles along the path then you can step through that vector and make the character walk to each tile in turn.

Code:
std::vector<sf::Vector2f> path; //this is just a simple vector of tile (x,y) locations


void Imp::followPath(float tick){
    float dx,dy;
    bool reachingDestination=false;
    //calculate the current path tile the imp is occupying
    pathCurrent.x = floor(position.x / myLevel->tileset.twidth)*myLevel->tileset.twidth;
    pathCurrent.y = floor(position.y / myLevel->tileset.theight)*myLevel->tileset.twidth;

    typeof(path.begin()) it = find(all(path), pathCurrent); //find the current path tile the imp is occupying
    //pathnext is the location of the next tile in the path
    if (++it != path.end()){//path.size()>1){
        //++it;
        pathNext = *it;
    }
    else{
        //this must mean we're arriving at desitnation... TOOT TOOT
        pathNext = pathCurrent;
        reachingDestination = true;
    }
    dx = position.x - pathNext.x; //when "next" is to the right (larger) gives negative dx
    dy = position.y - pathNext.y; //when next is below (larger) gives negative dy
    if (abs(dx) > speed*tick || abs(dy) > speed*tick){
        if (abs(dx) > abs(dy)){
            if (position.y - pathCurrent.y > speed*tick)
                setDirection(UP);
            else{
                if (dx < 0)
                    setDirection(RIGHT);
                else
                    setDirection(LEFT);
            }
        }
        else{
            if (position.x - pathCurrent.x > speed*tick)
                setDirection(LEFT);
            else{
                if (dy < 0)
                    setDirection(DOWN);
                else
                    setDirection(UP);
            }
        }
        move(tick);
    }
    else{
        if (reachingDestination){
            //destination reached!
            if (hasCoffee){
                requestExit();
            }
            else{
                requestGather();
            }
        }
        else {
            //this happens if the imp gets a litt bit "stuck" on its journey
            move(tick);
        }
    }
}

_________________
Whatever the mind can conceive and believe, it can achieve


Top
 Profile  
 
PostPosted: Thu Mar 29, 2012 7:12 pm 
Bytewise

Joined: Sun Oct 16, 2011 3:09 pm
Posts: 282
Location: Here (where else?)
An alternative could be to run the A*, and then only take the path to the next tile or to the next corner, or so.
When reaching that point run the algorithm again, take the first part, etc

It costs more CPU, but mario can adapt to new situations faster.

_________________
My project: Messing about in FreeRCT, dev blog, and IRC #freerct at oftc.net


Top
 Profile  
 
PostPosted: Mon Apr 02, 2012 7:28 pm 
Rookie

Joined: Thu Mar 29, 2012 2:05 am
Posts: 4
thank you for replying guys but so far i tried all your suggestions but it still didn't works i think i don't know maybe i miss something... i saw a lot of tutorials but none of them made it the way i do it.. it is very frustrating that i came that far to abandoned the project.


Top
 Profile  
 
PostPosted: Tue Apr 03, 2012 8:21 pm 
Bytewise

Joined: Sun Oct 16, 2011 3:09 pm
Posts: 282
Location: Here (where else?)
I'd suggest to scale it down to the bare minimum.
To move Mario, you don't need A*, key handling, logging, files, mouse, getters/setters. A path can be just a single line.

Personally, I am not reading that much code to figure out where your problem is.

_________________
My project: Messing about in FreeRCT, dev blog, and IRC #freerct at oftc.net


Top
 Profile  
 
PostPosted: Wed Apr 04, 2012 2:49 pm 
Rookie

Joined: Thu Mar 29, 2012 2:05 am
Posts: 4
Alberth wrote:
I'd suggest to scale it down to the bare minimum.
To move Mario, you don't need A*, key handling, logging, files, mouse, getters/setters. A path can be just a single line.

Personally, I am not reading that much code to figure out where your problem is.



i know i don;t need A* if i only want to move mario on mouse click but my main goal was to use A star algorithme thank you for your suggestion i am still trying to figured out how to do it.


Top
 Profile  
 
PostPosted: Wed Apr 04, 2012 5:02 pm 
Funky Monkey

Joined: Thu Sep 09, 2004 1:17 pm
Posts: 1567
Location: burrowed
What exactly is the problem that troubles you?

_________________
Long pork is people!

wzl's burrow


Top
 Profile  
 
PostPosted: Wed Apr 04, 2012 6:41 pm 
Bytewise

Joined: Sun Oct 16, 2011 3:09 pm
Posts: 282
Location: Here (where else?)
3rdnubas3 wrote:
Alberth wrote:
I'd suggest to scale it down to the bare minimum.
To move Mario, you don't need A*, key handling, logging, files, mouse, getters/setters. A path can be just a single line.

Personally, I am not reading that much code to figure out where your problem is.



i know i don;t need A* if i only want to move mario on mouse click but my main goal was to use A star algorithme thank you for your suggestion i am still trying to figured out how to do it.
My point about scaling down was not to discourage you from using any algorithm, it was about making the problem smaller.

If it does not work, and you don't know why, it is too big to understand.

A proven way to get out of this situation is to reduce the problem. This works in two ways. One advantage is that the problem you're facing gets smaller. If you drop a piece, and it still fails, you know that the piece was not the cause. If it does start working, you know that the last part you dropped does something weird.

In the worst case, you run out of pieces to drop, and it still fails. In that case, you should have something small enough to show others, and ask for input.
(People reading a forum don't spend a day reading your code and trying to imagine what might go wrong. As a result, they can manage only very small pieces of code. (Would you solve my problem if I sent you 8 pages of code you've never seen?))



Once you found the problem, you can either transplant the solution back in your original setup, or you can gradually assemble the pieces back together, checking that it continues to work.

_________________
My project: Messing about in FreeRCT, dev blog, and IRC #freerct at oftc.net


Top
 Profile  
 
PostPosted: Mon Apr 09, 2012 6:10 am 
Rookie

Joined: Thu Mar 29, 2012 2:05 am
Posts: 4
weezl wrote:
What exactly is the problem that troubles you?
i am trying to learn from scratch and made an Astar class very simple base on the wiki algorithm and other online tutorials. it worked so far i was able to display the path found graphics squares. so what i need from now is how to i make my hero or character follow this path... i have tried a lot of stuffs but none i have worked. basically i don't understand how to make the hero follow.... i understand the concept but so far i can't make it work...
voila ! that's is my problem unfortunately


Top
 Profile  
 
PostPosted: Tue Apr 10, 2012 4:29 pm 
Funky Monkey

Joined: Thu Sep 09, 2004 1:17 pm
Posts: 1567
Location: burrowed
Basic path following can be done through your single path nodes.

Have your character walk towards the next path node (i.e. square produced by your a*), you do that by determining the direction of the path node from your character.

Code:
Vector target = PathNode[nextNodeIndex] - character.Position;
target.normalize();
character.Position += target * deltaTime * moveSpeed;


as soon as your character comes within close proximity of the node it is walking towards you increment on it so the node will be it's target.

Code:
if((character.Position - PathNode[nextNodeIndex]).Length < closeDistance)
  nextNodeIndex++;


You repeat this until your nextNodeIndex is bigger than the node count of your a* path nodes. At this point the character has reached it's destination.

You can use different methods to optimize your path to reduce the number of nodes, or smooth it out so diagonal paths are not all zigzaggy, but the way you traverse those path nodes remain the same.

_________________
Long pork is people!

wzl's burrow


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 11 posts ] 

All times are UTC


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
Jump to:  
Powered by phpBB® Forum Software © phpBB Group