This site requires JavaScript, please enable it in your browser!
Greenfoot back
Dudesame
Dudesame wrote ...

2017/6/16

A better alternative to getOneAtOffset?

Dudesame Dudesame

2017/6/16

#
I want a better alternative to getOneAtOffset. my enemies are large and the location where the bullet registers a hit is too small. here is my current enemy code.
 
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Enemy3 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Enemy3 extends Player
{
    /**
     * Act - do whatever the Enemy3 wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    private int health = 20;
private int timerPistol; 
public int direction; 
public void Shot()
{
    Actor bullet = getOneObjectAtOffset(0, 0, Bullet.class);
    if (bullet != null)
    {
        getWorld().removeObject(bullet);
        health--;
        if (health == 0) getWorld().removeObject(this);
        Greenfoot.playSound("Minecraft Hit Sound.mp3");
}
}
    public void act() 
    {
        move();
        Shot();
        if (timerPistol > 0) {
        timerPistol--; // run timer
    }
        if (timerPistol == 0)
    {
        BulletZombie b = new BulletZombie();
        getWorld().addObject(b, getX(), getY());
        direction = getRotation();
        b.setRotation(direction);
        //Greenfoot.playSound("");
        timerPistol = 180; // start timer (adjust value as needed)
    }   
}
     public void move() 
    {
        move(1);
   if (getWorld().getObjects(FrenchMan.class).isEmpty()) return;  
        Actor FrenchMan = (Actor)getWorld().getObjects(FrenchMan.class).get(0);
        turnTowards(FrenchMan.getX(), FrenchMan.getY()); 
    
    }    
}
Yehuda Yehuda

2017/6/16

#
You can use getOneObject(...) instead, but I don't think you need to. The 'shot' method can be the following.
private void shot() {
    if (isTouching(Bullet.class)) {
        Greenfoot.playSound("Minecraft Hit Sound.mp3");
        removeTouching(Bullet.class);
        health--;
        if (health == 0) getWorld().removeObject(this);
    }
}
Dudesame Dudesame

2017/6/16

#
Works like a miracle, thank you.
You need to login to post a reply.