2012-03-17 10 views
0

기본적으로 자바에서 톱 다운 슈터를 만들고 있습니다. 총알에는 모든 속성과 업데이트 방법 및 내용을 담은 총알 개체가 있습니다. 나는 마우스를 누르고 개체의 인스턴스가 만들어지면 배열 목록을 사용하여 글 머리 기호를 저장하기로 결정했습니다. 문제는 배열 목록에서 요소를 식별하는 방법을 모른다는 것입니다. 다음은 간단한 배열을 사용했을 때 코드 일부를 보여줍니다.배열 목록에서 개체의 속성을 변경하는 방법은 무엇입니까?

addMouseListener(new MouseAdapter(){ 
    public void mousePressed(MouseEvent e){ 
     pressedX = e.getX(); 
     pressedY = e.getY(); 


     bullets[bulletCount] = new Bullet(player.x, player.y)); 
     double angle = Math.atan2((pressedY - player.y),(pressedX - player.x)); 
    bullets[bulletCount].dx = Math.cos(angle)*5; 
    bullets[bulletCount].dy = Math.sin(angle)*5; 
    bulletCount++; 


    } 

어떤 도움을 주시면 감사하겠습니다! 미리 감사드립니다!

+0

무엇을 식별하려고합니까? 특정 글 머리 기호입니까? – twain249

답변

3

당신은 바로 이런 일을 변경할 수 있습니다 :

bullets[index].foo 

bullets.get(index).foo 

그러나 코드에서 당신이 준

에, 우리는 더 잘 할 수 있습니다.

그래서 :

addMouseListener(new MouseAdapter() { 
    public void mousePressed(MouseEvent e) { 
     int pressedX = e.getX(); 
     int pressedY = e.getY(); 

     Bullet bullet = new Bullet(player.x, player.y); 
     double angle = Math.atan2((pressedY - player.y), (pressedX - player.x)); 
     bullet.dx = Math.cos(angle)*5; 
     bullet.dy = Math.sin(angle)*5; 
     bullets.add(bullet); 
    } 
} 

이제 여전히 액세스하는 것 필드 나에게 아주 좋은 생각이 아닌 것 같아 직접 총알에. 내가 제안하는 dxdy위한 중 하나를 사용 특성 - 또는 생성자의 일부 만들기 - 가능성 또는 복용 단일 특성 (기본적으로 DX와 DY의 벡터 것)을 Velocity :

addMouseListener(new MouseAdapter() { 
    public void mousePressed(MouseEvent e) { 
     // Again, ideally don't access variables directly 
     Point playerPosition = new Point(player.x, player.y); 
     Point touched = new Point(e.getX(), e.getY()); 

     // You'd need to put this somewhere else if you use an existing Point 
     // type. 
     double angle = touched.getAngleTowards(playerPosition); 
     // This method would have all the trigonometry. 
     Velocity velocity = Velocity.fromAngleAndSpeed(angle, 5); 

     bullets.add(new Bullet(playerPosition, velocity)); 
    } 
} 
+0

감사합니다. 시험을 치러야합니다 !! – hazard1994

+0

Jon Skeet 당신은 내 영웅입니다 !! 치료를해라! 도와 주셔서 감사합니다!! – hazard1994

+0

추가 도움 주셔서 감사합니다. – hazard1994

관련 문제