I have 3 images and 1 button -
I want to be able to click my button and have 1 of the 3 images appear. And everytime I click the button i want a new random image to appear in the place of the last image......Pretty simple it would seem, but Im losing hair over this and am about to call it quits......Can anyone help me do this? I want to learn, so please comment the code if you decide to help me....Thanks in advance.
So far, I have:
display.setStatusBar( display.HiddenStatusBar ) -- hide status bar
--insert background
local bgImg = display.newImageRect( "images/myBG.jpg", 625, 450 )
bgImg.x = display.contentCenterX -- center bg on X
bgImg.y = display.contentCenterY -- center bg on Y
-- scripture references
myTable = {
display.newImage("images/btnLogo1.png"),
display.newImage("images/btnLogo2.png"),
display.newImage("images/btnLogo3.png"),
}
randomPicture = myTable[math.random(1,3)]
This should work:
-- scripture references
myTable = {
"images/btnLogo1.png",
"images/btnLogo2.png",
"images/btnLogo3.png",
}
local randomPicture = myTable[math.random(1,3)]
display.newImage(myTable[randomPicture])
I hope you need no explanation about it :)
If your image names are continous, that is like img_1,img_2,img_3. etc... then you can use the following method:
-- Display an image
local myImage = display.newImageRect("images/btnLogo1.png",50,50)
myImage.x = display.contentWidth/2
myImage.y = display.contentHeight/2
-- Call this function on button click
function imageChangeFunction()
-- remove the previous image
if(myImage)then myImage:removeSelf() end
-- creating the sprite with new image
myImage = display.newImageRect("images/btnLogo"..math.random(3)..".png",50,50)
myImage.x = display.contentWidth/2
myImage.y = display.contentHeight/2
print("Image changed...")
end
-- Here I am assigning the listener to Runtime, you can change it for your button
Runtime:addEventListener("tap",imageChangeFunction)
Note:
math.random(3) gives you any random number between 1 and 3.
.. is used for concatenation. So, "images/btnLogo"..math.random(3)..".png" will give you any of the following strings:
images/btnLogo1.png
images/btnLogo2.png
images/btnLogo3.png
For more info, visit: math.random() and Corona String Operations
Related
Hello roblox studio scripters,
I'm a intermediate scripter-builder and need some help with the gui for my game.
I have a start screen with a play button like this:
I'm trying to fade out the gui when the button is clicked, but none of the tutorials worked. This is my script for the button:
local button = script.Parent
local gui = script.Parent.Parent.Parent
button.MouseButton1Down:Connect(function()
gui.Enabled = false
end)
I don't know how to do the changing, would it be BackgroundTransparency? How would you change the transparency from 0 to 1 in 0.01 increments?
I tried to make the gui fade with a for loop, changing the BackgroundTransparency but that didn't work, this is that code:
local button = script.Parent
local gui = script.Parent.Parent.Parent
button.MouseButton1Down:Connect(function()
for i = 0, 100, 1 do
gui.Frame.BackgroundTransparency + 0.01
wait(0.01)
gui.Enabled = false
end
end)
I don't know why it isn't working.
If I have a typo or something, please tell me.
Thanks!
The loop solution has a few typos, here it is fixed:
local button = script.Parent
local gui = script.Parent.Parent.Parent
button.MouseButton1Down:Connect(function()
for i = 0, 100 do
gui.Frame.BackgroundTransparency += 0.01 -- += adds 0.01 each time
task.wait(0.01) -- better than wait(0.01)
end
gui.Enabled = false
end)
However, this is not an ideal solution. A better system would use Roblox's TweenService to change the gui's transparency. Tweens are less jittery, are easier to modify, and have lots of customisation properties including repeating, changing length of time, and style of easing (e.g. going faster at first, then slower near the end; see Easing Styles on the Roblox docs).
local TweenService = game:GetService("TweenService")
local button = script.Parent
local gui = script.Parent.Parent.Parent
local tweenInfo = TweenInfo.new(
2, -- Time
Enum.EasingStyle.Linear, -- Easing Style
Enum.EasingDirection.Out -- Easing Direction
-- See https://create.roblox.com/docs/reference/engine/datatypes/TweenInfo for more available properties
)
local tween = TweenService:Create(
gui.Frame, -- Instance to tween
tweenInfo, -- TweenInfo
{ Transparency = 1 } -- What we want to change
)
button.MouseButton1Down:Connect(function()
tween:Play()
tween.Completed:Wait() -- Wait until tween is complete
gui.Enabled = false
end)
Though both of these solutions change only the transparency of the background, so the child elements, such as the Playbutton, will stay visible until the gui is disabled. You may wish to replace the Frame with a CanvasGroup, which also changes the transparency of its children when its GroupTransparency property is changed.
local tween = TweenService:Create(
gui.CanvasGroup, -- Instance to tween
tweenInfo, -- TweenInfo
{ GroupTransparency = 1 } -- What we want to change
)
I have some code here that when an image (which is my button) is clicked, a new image randomly appears. This is due to a table I created with some images inside.
local animalPic
local button = display.newImageRect ("images/animalBtn.jpg", 200, 200)
button.x = 250
button.y = 50
local myPics = {"images/animal1.png", "images/animal2.png"}
function button:tap (event)
local idx = math.random(#myPics)
local img = myPics[idx]
local animalPic = display.newImage(img)
animalPic.x = contentCenterX
animalPic.y = contentCenterY
end
button:addEventListener ("tap", button)
The problem with it is the graphics just keep piling up when I click the button. The correct behavior should be -
Button is clicked and an image is shown while removing the previous image. How do I incorporate this behavior? I already tried the removeSelf command and it doesnt work......Any help appreciated.
You declare animalPic each time you enter function. You should declare it once and then remove it and replace it by another.
It should be:
local animalPic
function button:tap (event)
local idx = math.random(#myPics)
local img = myPics[idx]
animalPic:removeSelf()
animalPic = nil
animalPic = display.newImage(img)
animalPic.x = contentCenterX
animalPic.y = contentCenterY
end
When you call display.newImage(), you are adding a new image. The problem is that you need to remove/hide the original one. Perhaps you really need two objects - one for the current image and one for the tap event. When the tap event occurs, hide the old image and display the new one. An alternative would be to load all the images in their own imageRects and then toggle them on and off.
I want to save images without overwriting them whenever I hit the pushbutton. Can you please help me how save images without overwriting the original? What I want to do is whenever I'll hit the pushbutton, It will generated 1 image at a time without deleting the original.
Just like in digital cameras, whenever I will hit the trigger button, it will save 1 image and the file name will be image1.jpg. So basically, if I will push trigger again, it will capture 1 image again and the file name will be image2.jpg and so on.
here is my code:
counter = 1; %initialize filename increment
vid = videoinput('winvideo',2);
set(vid, 'ReturnedColorSpace', 'RGB');
img = getsnapshot(vid);
imshow(img);
savename = strcat('C:\Users\Sony Vaio\Documents\Task\images\image_' ,num2str(counter), '.jpg'); %this is where and what your image will be saved
imwrite(img, savename);
counter = counter +1; %counter should increment each time you push the button
My code saves and keeps on overwriting the filename image1.jpg.
To make things clear
1 push to the pushbutton, 1 image saves.
it's like it will call the whole block code every hit at pushbutton.
I hope you guys can help me. I really troubled right now :(
Thank you :)
If this is the code that makes up the callback function for that pushbutton, then yes indeed, it will execute the entire block every time you push it.
If that is the case, you'll need to change it to this:
%// initialize filename increment
persistent counter;
if isempty(counter)
counter = 1; end
vid = videoinput('winvideo', 2);
set(vid, 'ReturnedColorSpace', 'RGB');
img = getsnapshot(vid);
imshow(img);
%// this is where and what your image will be saved
savename = [...
'C:\Users\Sony Vaio\Documents\Task\images\image_', ...
num2str(counter), '.jpg'];
imwrite(img, savename);
%// counter should increment each time you push the button
counter = counter + 1;
or, you could check what files are actually present, and use the next logical filename in the sequence:
vid = videoinput('winvideo', 2);
set(vid, 'ReturnedColorSpace', 'RGB');
img = getsnapshot(vid);
imshow(img);
%// this is where and what your image will be saved
counter = 1;
baseDir = 'C:\Users\Sony Vaio\Documents\Task\images\';
baseName = 'image_';
newName = [baseDir baseName num2str(counter) '.jpg'];
while exist(newName,'file')
counter = counter + 1;
newName = [baseDir baseName num2str(counter) '.jpg'];
end
imwrite(img, newName);
Every time you push that button the counter value resets to 1 because of the very first statement:
counter = 1
and hence the error.
counter = length(dir('*.jpg')) + 1; %Counts the number of .jpg files in the directory
That should do the job.
Zaher:
I'm online program about image processing and image acquisition from the camera in writing MATLAB.
When receiving the image every few seconds I get a picture of the camera.
Photos must be stored and processed in statistical process control charts.
When the first image after image acquisition program hangs and stops.
Please code to get images every 10 seconds online from cameras send images that can be used in statistical process control.
Thank
I am trying to get my buttons to stay "pressed" once it is released. Right now I am using the improved Buttons Module for corona and I have the default image being the button looking unpressed, and the over image being replaced by an image that looks pressed.
What I am trying to do is once the button is pressed, it stays on the over image. Here is how my code is set up for the button I am testing it on.
local digButton = buttons.newButton{
default = "digButton.png",
over = "digButtonPressed.png",
onEvent = digButtonFunction,
id = "dig"
}
digButton:setReferencePoint(display.CenterReferencePoint)
digButton.x = display.contentWidth/5
digButton.y = display.contentHeight/1.9
Also, I have a function (digButtonFunction) that sets the id of this button to a variable to be used to run an if statement for when the user pushes a button following this one.
This sounds to me like what you really want is a switch. Buttons are not really designed from a UI perspective to do that. The down-state is there just to give feedback to the user that some action happened.
If it were me, I'd not use the button bit at all, but load in to images using display.newImageRect() and draw the downstate first, then the upstate. Built a touch event listener on each one that will hide one or the other. I do this in my games for my sound on/off buttons.
local soundOn = true
local soundOnBtn, soundOffBtn
local function soundToggle(event)
if soundOn then
soundOn = false
soundOnBtn.isVisible = false
soundOffBtn.isVisible = true
else
soundOn = true
soundOnBtn.isVisible = true
soundOffBtn.isVisible = false
end
return true
end
soundOnBtn = display.newImageRect("images/switch_on.png", 46, 36)
soundOnBtn.x = display.contentWidth / 2 + 25
soundOnBtn.y = display.contentHeight / 2 - 15
group:insert(soundOnBtn)
soundOnBtn:addEventListener("tap", soundToggle)
soundOffBtn = display.newImageRect("images/switch_off.png", 46, 36)
soundOffBtn.x = display.contentWidth / 2 + 25
soundOffBtn.y = display.contentHeight / 2 - 15
group:insert(soundOffBtn)
soundOffBtn:addEventListener("tap", soundToggle)
soundOffBtn.isVisible = false
I have such code:
a=5;
b=a;
c=10;
u = (0:0.05*pi:2*pi)'; %'
v = [0:0.05*pi:2*pi];
X = a*sin(u)*cos(v);
Y = a*sin(u)*sin(v);
Z = c*cos(u)*ones(size(v));
Z(Z>0)=0; % cut upper
V1=4/3*pi*a*b*c;
d=1/2;
e=2^d;
a2=a/e;
b2=a/e;
c2=c;
V2=4/3*pi*a2*b2*c2;
X2 = a2*sin(u)*cos(v);%-2.5;
Y2 = b2*sin(u)*sin(v);
Z2 = c2*cos(u)*ones(size(v));%+0.25;
Z2(Z2>0)=0; % cut
h=1/3;
for j = 1:20
k1=(sin(pi*j/20)+0.5)^h;
a=a*k1;
c=c*k1;
X = a*sin(u)*cos(v);
Y = a*sin(u)*sin(v);
Z = c*cos(u)*ones(size(v));
Z(Z>0)=0;
a2=a2*k1;
b2=a2*k1;
c2=c2*k1;
X2 = a2*sin(u)*cos(v)+5;%-2.5;
Y2 = b2*sin(u)*sin(v);
Z2 = c2*cos(u)*ones(size(v));%+0.25;
Z2(Z2>0)=0;
hS1=surf(X,Y,Z);
alpha(.11)
hold on
hS2=surf(X2,Y2,Z2);
hold off
axis([-20 20 -20 20 -20 20]);
F(j) = getframe;
end
movie(F,4)
I have to input parameters a,b,c from the keyboard. I've made GUI & tried to do it by using "Edit text" with a function below, but it's not working((.
I can't understand what's the problem with it.
function a_edit_Callback(hObject, eventdata, handles)
user_entry = str2double(get(hObject,'string'));...
a=user_entry;
The problem is that your callback function executing your code is not 'seeing' the parameters you defined in your edit text callbacks. You need to establish your variables in the subfunction, since they aren't global.
Using guide, set up a uicontrol button to click when you've entered your parameters into your uicontrol edit text boxes. Under the callback of your button, place your above code, with the following at the top:
a=str2double(get(handles.a_edit,'String'));
b=str2double(get(handles.b_edit,'String'));
c=str2double(get(handles.c_edit,'String'));
This will pull in the current strings of your edit text uicontrols. (Assuming you've assigned the tag format x_edit for each of the edit text boxes in guide.)
EDIT:
Open the figure you already created with the edit text boxes. Next, check to make sure each of your text boxes have the tag a_edit, b_edit, c_edit by using the property inspector. Then create a button using guide, and open the property inspector by double clicking on it. Find the 'tag' field, and name it run. Save your figure, and open the corresponding M-file.
Next, find the line with run_Callback(hObject, eventdata, handles). Place the following under it:
a=str2double(get(handles.a_edit,'String'));
b=str2double(get(handles.b_edit,'String'));
c=str2double(get(handles.c_edit,'String'));
%# Add the rest of your code from above verbatim, minus the first three lines
This should be the ONLY code you add to the auto-generated M-file - don't mess with anything else until you get this much working. If you don't want the animation popping up randomly in your figure window, you can add a set of axes using guide as well.
From the looks of the code, it appears to be a 'script' and not a 'function'.
Did you just want a 'dialog (built-in GUI dialog)'? If so, you can add the following at the beginning of your script:
prompt = {'Enter the parameter value "a":','Enter the parameter value
"b":','Enter the parameter value "c":'};
dlg_title = 'Input the Parameter Values';
num_lines = 1;
def = {'5','5','10'};
answer = inputdlg(prompt,dlg_title,num_lines,def);
a=answer{1};a=str2double(a);
b=answer{2};b=str2double(b);
c=answer{3};c=str2double(c);
% Y.T.