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

2019/6/13

How do I get a clicked object?

CP7 CP7

2019/6/13

#
How do I get a clicked object?
Nosson1459 Nosson1459

2019/6/13

#
do you mean to ask how do you make an object do something when clicked on? if that's what you want to know then here's the answer if not please tell me. you insert this if statement into the coding of the object you want to activate when clicked on:
if(Greenfoot.mouseClicked(this))
{
    //what you want the actor to do when clicked on
}
CP7 CP7

2019/6/13

#
I basically wanna do this:
if (Greenfoot.mouseClicked(Card.class))
{
    Card card = //(get clicked object);
    currentValue = card.getCurrentValue();
}
I have a deck and multiple cards on the screen, with different suits and values and I want to get the value and suit of the clicked card when it's clicked
Super_Hippo Super_Hippo

2019/6/13

#
The "mouseClicked" method requires an object, not a class. So you either do it like Nosson suggested and check a click in the Card class' act method and then send the value to where ever you need it. Or the object in which you need the value has a reference to the card object and then can check for a click on that object.
CP7 CP7

2019/6/14

#
Could you please provide the code for it?
Super_Hippo Super_Hippo

2019/6/14

#
That depends on which way you want to go.
CP7 CP7

2019/6/14

#
Like the way I have it above
Super_Hippo Super_Hippo

2019/6/14

#
Is that code in the active world?
CP7 CP7

2019/6/14

#
Yes
Super_Hippo Super_Hippo

2019/6/14

#
//reference to the card
private Card card;
//you will most likely replace that with an array of cards if you have multiple ones, but first, let's take it simple


//creating the card and adding it to the world
addObject(card = new Card(), <x>, <y>);


//checking if a click on the card happened
if (Greenfoot.mouseClicked(card)) //I personally prefer mousePressed but that's obviously up to you
{
    //…
}
CP7 CP7

2019/6/14

#
Sorry, I should've explained this better, but I have multiple cards on the screen, so lets say a 7 of Hearts and 2 of Spades in my hand. When I click on the 7 of Hearts, I want to specifically get that card and call the method card.getCardValue(), which would return "7".
Super_Hippo Super_Hippo

2019/6/14

#
//reference to all cards in hand
private ArrayList<Card> cardsInHand = new ArrayList<Card>();

//whenever card x moves to the hand
cardsInHand.add(x);

//whenever card x is removed from the hand
cardsInHand.remove(x);

//check if any card is clicked
for (Card card : cardsInHand)
{
    if (Greenfoot.mouseClicked(card))
    {
        //call card.getCardValue() here and do with it whatever you want
    }
}
You need to login to post a reply.