In Unity, how can i instantiate 4 images that are clickable? - unity3d

Id like to make a language learning game but im trying to instantiate images that are clickable and have 4 instantiate where one is correct and when all 4 are instantiated an audio clip plays that is associated with one of the images.

First I would make a Class to manage that each Image has an associated AudioClip.
class Answers{
AudioClip clip;
Sprite img;
}
Then you can create as many Answers as you choose (here 1 as an example)
AudioClip clip1; // define in inspector
Answers[] answers = {Resources.Load <Sprite>("name_of_the_sprite"), clip1}; // Sprite with the name will be loaded in runtime
Instead of instantiating new Images you should now just be able to edit the same ones. Because only the Image on the objects and the audio clip needs to change.
To manage that, we write a Function:
// Defining Images that we want to change
public Image img1;
public Image img2;
public Image img3;
public Image img4;
// Call it each time you want to change the Answers
public void ChangeImages()
{
// Selecting 4 Random Images
Answers a1 = answers[answers.RandomRange(0, answers.Count)];
Answers a2 = answers[answers.RandomRange(0, answers.Count)];
Answers a3 = answers[answers.RandomRange(0, answers.Count)];
Answers a4 = answers[answers.RandomRange(0, answers.Count)];
// Change Sprite of the Images
img1.sprite = a1.img;
img2.sprite = a2.img;
img3.sprite = a3.img;
img4.sprite = a4.img;
// To make that random just make a switch statement
int randomnumber = Random.Range(1, 5)
// Correct Solution
int correctImage = 0;
// Play your audioclip, for which every Image you want to be correct
switch (randomnumber)
{
case 1:
PlayAudioClip(a1.clip);
correctImage = 1;
break;
case 2:
PlayAudioClip(a2.clip);
correctImage = 2;
break;
case 3:
PlayAudioClip(a3.clip);
correctImage = 3;
break;
case 4:
PlayAudioClip(a4.clip);
correctImage = 4;
break;
}
}
If the player now clicks on an Image you can check if it was the correct one with the correct Image number and depending on that let the player continue or end the game.

Related

How to change texture format from Alpha8 to RGBA in Unity3d?

I have been trying to change the format from a camera that give a texture in Alpha8 to RGBA and have been unsuccessful so far.
This is the code I've tried:
public static class TextureHelperClass
{
public static Texture2D ChangeFormat(this Texture2D oldTexture, TextureFormat newFormat)
{
//Create new empty Texture
Texture2D newTex = new Texture2D(2, 2, newFormat, false);
//Copy old texture pixels into new one
newTex.SetPixels(oldTexture.GetPixels());
//Apply
newTex.Apply();
return newTex;
}
}
And I'm calling the code like this:
Texture imgTexture = Aplpha8Texture.ChangeFormat(TextureFormat.RGBA32);
But the image gets corrupted and isn't visible.
Does anyone know how to change this Alpha8 to RGBA so I can process it like any other image in OpenCV?
A friend provided me with the answer:
Color[] cs =oldTexture.GetPixels();
for(int i = 0; i < cs.Length; i++){//we want to set the r g b values to a
cs[i].r = cs[i].a;
cs[i].g = cs[i].a;
cs[i].b = cs[i].a;
cs[i].a = 1.0f;
}
//set the pixels in the new texture
newTex.SetPixels(cs);
//Apply
newTex.Apply();
This will take alot of resources but it will work for sure.
If you know a better way to make this change please add an answer to this thread.

How to compare two sprite textures in unity

I have a requirement of comparing two sprite textures for knowing those two sprites belongs to same image or not. Here those textures are loaded from urls. Thanks in advance.
Here is the sample code for getting sprite texture:
WWW imageLink = new WWW(imageUrl);
var spriteTexture = imageLink.texture;
In on of my case same image with two different urls. Once url is loaded, have a requirement of identifying those textures have belongs to same image. Please suggest any idea.
There is no easy util to compare the two textures, but luckily it's easy to write one. The method of Texture2D.GetPixels() will give you a Color[] array which represents a flattened 2d array of pixel colors. Each row of pixels will be placed one after the other, starting from the bottom to the top. Comparing the two arrays should prove the two textures are identical. I tried this code:
private bool CompareTexture (Texture2D first, Texture2D second)
{
Color[] firstPix = first.GetPixels();
Color[] secondPix = second.GetPixels();
if (firstPix.Length!= secondPix.Length)
{
return false;
}
for (int i= 0;i < firstPix.Length;i++)
{
if (firstPix[i] != secondPix[i])
{
return false;
}
}
return true;
}
With you code, you will simply need to call:
WWW imageLink = new WWW(imageUrl1); //first image URL
WWW imageLink2 = new WWW(ImageUrl2); //second image URL
if (CompareTexture(imageLink.texture, imageLink2.texture) {
....
}
To compare both textures.

Randomly colored objects spawner in unity [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
trying to make a game, i need to make a spawner spawns objects in four colors randomly when we click Fire1 button, in limit number for example 4 times red for time blue.. Etc but randomly and the spawner shows the coming color or the next color, i tried many things but didn't work for me. Any help plz.
I can give you an idea of how to complete it -
First things first I'd say create the 4 game objects you'd like to use in your game in your editor, and assign the appropriate 4 colours in the objects material that you'd like to use.
Create a new folder in your assets called 'Resources' Then Create a Prefab for these objects by dragging them from your project hierarchy into your Resources folder.
Now Create a new empty gameobject and a new C# script in your assets folder, and drag the C# script onto the new empty game object. Inside the C# Script you want a few methods, the following should do the trick given that the prefabs are called shape1, shape2 etc.
//shapes to be spawned
public List<GameObject> shapes;
//shapes that are in game
public List<GameObject> spawnedShape;
//num of next shape to be places
public int next;
//list of shapes that can be spawned
public List<int> shapeCount;
System.Random random;
void Start()
{
random = new System.Random();
for (int i = 0; i < 4; i++)
{
//adds shapes that can be added into shapecount list.
for(int j = 0; j < 4; j++)
{
shapeCount.Add(i);
}
//load game objects from resources into list
GameObject go = Resources.Load("shape" + i) as GameObject;
shapes.Add(go);
}
//set next shape
int next = setNext();
}
void Update()
{
if (Input.GetButton("Fire1")) {
spawnShape();
}
}
public int setNext()
{
if (shapeCount.Count != 0)
{
int num = random.Next(0, shapeCount.Count);
return shapeCount[num];
}
else return -1;
}
void spawnShape()
{
if(next == -1)
{
Debug.Log("Out of shapes");
}else
{
//creates instance of shape
GameObject go = Instantiate(shapes[next]);
//creates and assigns random x, y coordinate
int x = random.Next(0, 500);
int y = random.Next(0, 500);
go.transform.position = new Vector3(x, y, 0);
spawnedShape.Add(go);
}
//gets colour of next shape
next = setNext();
}
Just adjust the code to fit your project, there are more efficient ways of doing it for instance having one shape and adding different materials however this way can allow for all different shapes.

Flash : How to write roll over coding for grid in array which is similar colour movieclips nearby?

Flash AS3:
I just need to know how to check a condition for roll over effect on similar colour movieclips which is near by in a group of random colours movieclips in a grid whereas it is using 2D Array in flash AS3.or
I just need roll over event which i wrote is onBoxOver event function, in that the object which i am targetting is only getting rollover or getting alpha changes. But i need to know how to make rollover for similar colour which are all nearby.
The code which i wrote is below for your reference.
Flash AS3::
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class playGame extends MovieClip
{
public static var totalRowBoxes:Number = 13;
public static var totalColumnBoxes:Number = 12;
public static var rowGap:Number = 30;
public static var columnGap:Number = 30;
public static var totalColorBoxes:Number = 8;
public static var boxCollection:Array = new Array();
public static var boxCollection1:Array = new Array();
public function playGame(theGame:main)
{
// constructor code
addBoxOnStage();
}
private function addBoxOnStage():void
{
var borderCont:Banner = new Banner();
var scoreclipCont:scoreclip = new scoreclip();
addChild(borderCont);
addChild(scoreclipCont);
scoreclipCont.x = 0;
scoreclipCont.y = 0;
createLevel(1);
for (var i:Number = 0; i<totalRowBoxes; i++)
{
boxCollection[i] = new Array(i);
for (var j:Number = 0; j<totalColumnBoxes; j++)
{
var squareCont:square = new square();
squareCont.x = 30 + (i * rowGap);
squareCont.y = 30 + (j * columnGap);
squareCont.name = i + "_" + j;
var boxCollection1:Array = new Array();
boxCollection1[0] = Math.round(Math.random() * 8);
boxCollection1[1] = squareCont;
var boxColour:Number = new Number();
boxColour = boxCollection1[0];
boxCollection[i][j] = boxCollection1[1];
addChild(squareCont);
squareCont.gotoAndStop(boxCollection1[0]);
squareCont.addEventListener(MouseEvent.MOUSE_OVER, onBoxOver); squareCont.addEventListener(MouseEvent.MOUSE_OUT, onBoxOut);
squareCont.addEventListener(MouseEvent.CLICK, onBoxClick);
}
}
}
private function onBoxClick(eve:MouseEvent):void
{
}
private function onBoxOver(eve:MouseEvent):void
{
for (var i:Number=0; i< totalRowBoxes; i++)
{
for (var j:Number=0; j<totalColumnBoxes; j++)
{
eve.target.alpha = 0.3;
// trace(boxCollection[i][j].currentFrame)
trace(eve.target);
}
}
}
private function onBoxOut(eve:MouseEvent):void
{
eve.target.alpha = 1;
}
private function createLevel(lvl):void
{
}
}
}
![My Game screenshot here colourbox][1]
Thanks in Advance. Greatly Appreciable for the reply.
Hi this is the image or screenshot of my project. In that image there are 8 colours randomly arranged. whenever i make mouse position or rollover on any box , the condition should check whether the same colour occurs around the box(eg.top, down, left, right) which i am making rollover.
1.If the same colour occur on the top of the box which i am pointing the cursor , the top box and the box which i am pointing both should get less alpha, else only the pointing box should get less alpha. this is my concept friends. please go through the image and let me know if u have any doubts.
I am still unsure what you mean by 'nearby'. (neighbour tiles? adjacent of similar colour?...)
If 'nearby' means adjacent, you need to read about flood fill algorithms. There is a good wiki article about this. You would use that to crawl through the list of tiles similar enough to trigger the effect you want.
I also don't know what 'similar' colour means in your project. You will need a method to determine weather two colours are similar. There is a stackoverflow question re: similar colour detection. It has a good answer to start you out in your research. look here.

Pure ActionScript 3.0 - Memory Game

I'm a beginner of ActionScript 3.0. I'm making a simple memory game, the tool I'm using is Eclipse with flexsdk plugin. Right now I've done the shuffle and display images, and the cover of the images as well.
My idea is when clicking on the image, the cover will remove and show the image behind of it. After 2 covers are gone, the game will compare and check whether the selected images are match or not, if match both of the images will remain, otherwise the cover will reappear and the game keeps going on. If all of the images are match, a winning line will appear.
The problem I'm facing is I got no idea on how to deal with the images comparison part. I wanted to compare with the index number of array or the name of the images, but I really don't have any idea. I've refer some examples but all of them are develop in CS3 and uses the timeframe which is not exist in pure ActionScript.
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import myclasses.Cover;
public class Prototype extends Sprite {
protected static const WIDTH:int=3;
protected static const HEIGHT:int=2;
protected static const SPACINGX:int=100;
protected static const SPACINGY:int=74;
protected static const OFFSETX:int=96;
protected static const OFFSETY:int=100;
protected static const SIZE:Number=100;
protected static const COLOUR:uint=0x999999;
[Embed(source="images/pic1.jpg")]
protected static const PIC1:Class;
[Embed(source="images/pic2.jpg")]
protected static const PIC2:Class;
[Embed(source="images/pic3.jpg")]
protected static const PIC3:Class;
protected var imagesList:Array=[PIC1,PIC1,PIC2,PIC2,PIC3,PIC3];
protected var X:int;
protected var Y:int=27;
protected var count:int;
//protected var firstTap:Class;
//protected var secondTap:Class;
public function Prototype() {
var shuffled:Array = shuffleList(imagesList.length);
for(var i:int; i<imagesList.length; i++) {
//var colour:uint;
//colour=0x999999;
var j:int = shuffled[i];
var thing:Sprite=new Sprite();
thing.addChild(new imagesList[j]());
thing.x=X;
thing.y=Y;
addChild(thing);
new Cover(this,X,Y,SIZE,COLOUR);
X=X+SPACINGX+OFFSETX;
count++;
if(count == WIDTH){
Y=Y+SPACINGY+OFFSETY;
X=0;
}
addEventListener(MouseEvent.MOUSE_DOWN,selectImages);
}
}
public function selectImages(event:MouseEvent):void {
//(P/S: this is not the actual code)
var target:Sprite = Sprite(event.target)
if(firstTap == null){
firstTap = ; //1st selected image
removeChild(target);
}else if(secondTap == null){
secondTap = ; //2nd selected image
if(firstTap == secondTap){
firstTap = null;
secondTap = null;
}else{
//firstTap = ; //cover back
//secondTap = ; //cover back
secondTap = null;
firstTap = ; //selected another image
}
}
}
protected function shuffleList(n:Number):Array {
var startList:Array = new Array(n);
var endList:Array = new Array(n);
var i:Number, j:Number;
for (i=0; i<n; i++) {
startList[i] = i;
}
for (i=0; i<n; i++) {
j = Math.floor(Math.random()*startList.length);
endList[i] = startList.splice(j,1)[0];
}
return(endList);
}
}
}
Please help me figure out. Thanks.
Well I didn't really go through your code in details, but from looking at it, it seems you are making things really complex. So let me give you a hint in how I would do it...
1) First I would make a 'card' class, which extends sprite or bitmap, mainly containing the image of that card, image of the cover/mask, some animtion methods like hide/show e.t.c, and possibly an 'id' variable to recognize it later, though that is not needed. You can also get away with the array you have, and in that case, skip step 2.
2) Now push two copies of each card in an array.
example [new card('c1'),new card('c1'),new card('c2'),new card('c2'),.....].
3) Now comes the part where you made it most complex, that is, the shuffling of the array. Let's write a custom function for it, shall we?
function shuffleArr(arr):Array
{
var len:int = arr.length();
for(var i:int=0; i<len; i++)
{
//Swap the value at i with a random value within the array;
var tmp_pos:int = Math.floor(Math.random()*len);
while(tmp_pos==i)
{
tmp_pos = Math.floor(Math.random()*len);
}
var tmp_var:card = arr[tmp_pos];
arr[tmp_pos] = arr[i];
arr[i] = tmp_var;
}
}
4) Now that the array is shuffled, you simply have to lay them out in a grid.
for(var row:int=0; row<6; row++)
{
for(var col:int=0; col<6; col++)
{
card_arr[i].x = card_arr[i].width*cols+5;
card_arr[i].y = card_arr[i].height*row+5;
stage.addChild(card[i]);
}
}
5) Now you have to check for user click and take action, and there are many ways to do it, but I will tell one of them...
a) Give the cards a click event handler, this becomes easy if the cards are a class, or you can look into event.target property and use a general click handler. it's up to you.
b) On click, push the card's id in an array. If you did make them into a class, their ids should now be, c1, c2, e.t.c, and you can do
holder_arr.push(this);
this.removeCover();
6) Now you have to make sure, that the holder array can only hold two values at a time. Then do the checking. I am writing a semi-pseudo code with a lot of assumed functions and values:
//Insert
if(holder_arr.length()==2)
{
//flip back the cards and empty the array
holder_arr[0].showCover();
holder_arr[1].showCover();
holder_arr = [];
}
holder_arr.push(this);
...
..
7) For checking make a function and run it every time a card is clicked, and also when a timer ends, to flip back the cards.
function checkCards()
{
if(holder_arr.length==2)
{
if(holder_arr[0].id==holder_arr[1].id)
{
//the cards match
holder_arr[0].vanishAnim();
holder_arr[1].vanishAnim();
holder_arr=[];
}
else
{
holder_arr[0].showCover();
holder_arr[1].showCover();
holder_arr=[];
}
}
}
Obviously you will remove the cards from the actual card_arr too, but when to do that is up to you to figure out ;)
Personally , I find the problem has more to do with the way you shuffle your cards as it makes it a bit more difficult to identify what card is what.
Let's say for instance that instead of shuffling your embed assets , you were first creating your cards , naming them after the image they add , then creating an Array ( or Vector ) of cards and shuffle that Array ( or Vector ), identifying the cards would be fairly easy since you'd only have to compare their name property.
//PSEUDO CODE
- create Array ( Vector ) of embed assets [PIC1, PIC2 , PIC3]
- create cards and use Array ( Vector ) index to identify
each card with the name property
- create a set of six cards
- shuffle set