Corona - Touch Events In table objects? - events

I am trying to use this in a project, but I cannot figure out how to place a touch event listener to each of the icons/objects in the carousel, If someone could provide a quick answer of how to do that I'd appreciate it.
local NUM_ITEMS=20;
local radiusX= 200;
local radiusY= 40;
local centerX = 240;
local centerY = 160;
local speed = 0.05;
local perspective = 3;
local carousel = display.newGroup()
local icons = {}
local function zSort(myTable, myGroup)
table.sort(myTable,
function(a, b)
return a.depth < b.depth -- depth is your custom field
end
)
for i = 1, #myTable do
myGroup:insert(myTable[i].img)
end
end
function Icon(i)
local this = {}
local icon = display.newImage(carousel, "images/icon"..i..".png")
this.angle = (i-1) * math.rad(360/NUM_ITEMS);
this.img = icon
return this
end
function update(event)
local icon
local sin = math.sin
local cos = math.cos
for i=1, NUM_ITEMS, 1 do
icon = icons[i]
local img = icon.img
img.x = cos(icon.angle) * radiusX + centerX
img.y = sin(icon.angle) * radiusY + centerY
local s = (img.y - perspective) / (centerX + radiusY - perspective)
img.xScale = s*0.25
img.yScale = s*0.25
icon.angle = (icon.angle + speed) --%math.rad(360)
icon.depth = s
end
zSort(icons, carousel)
end
for i=1, NUM_ITEMS, 1 do
local icon = Icon(i)
icons[i] = icon
end
function onTouch(event)
if(event.phase=="moved") then
speed = (event.x - centerX) / 2000;
end
end
Runtime:addEventListener("enterFrame",update)
Runtime:addEventListener("touch", onTouch)

I can't exactly understood what you really need. But if you want to add individual touch to all same icons in a localGroup, then you can add the icons as an icon array and give specific tag to each and can give individual touch, as follows:
local icons = {}
for i=1,10 do
icons[i] = display.newImage(i..".png")
icons[i].tag = i
end
local function touchIt(e)
print(e.target.tag)
--[[ icons[e.target.tag] can be used to identify
and set properties to the touched icon --]]
end
for i=1,10 do
icons[i]:addEventListener("touch",touchIt)
end
OR
if you want to identify all group elements as the same and give touch, then you can use same tag/ give userdata to all icons and can give same touch action to all group elements(as follows).
local icons = {}
for i=1,10 do
icons[i] = display.newImage(i..".png")
icons[i].tag = 1 --[[ you can also use icons[i].userdata = "icons"
(or any string)--]]
end
local function touchIt(e)
print(e.target.tag) -- It willo be 1 for all icons
--[[ icons[e.target.tag] can be used to identify
whether if it is under 'icons' --]]
--[[ or use userdata as follows --]]
print(e.target.userdata)--[[ out put is a string
identifying the group/element--]]
end
for i=1,10 do
icons[i]:addEventListener("touch",touchIt)
end

Related

Frame not appearing when it is supposed to... (ROBLOX GUI)

I am making an Os module that lets you create remote Operating systems but when the background frame loads in a new window just an random window loads in but it just basically gets "overwritten" by the background frame.
I have a post on scriptinghelpers: https://scriptinghelpers.org/questions/116285/instancenew-but-not-working-as-expected-module
but it seems that no one wants no one on the website knows how to do it
my code for the main Os module:
local module = {}
function module.__Version__()
local ROS = '1.00'
local ROS = tostring(ROS)
print('Version: '..ROS)
end
function module.create_environment(master)
local main = Instance.new('ScreenGui',master)
main.Name = ("ROS")
return(main)
end
function module.create_background(env)
local Frame = Instance.new('Frame',env)
Frame.Name = ('Background')
Frame.Size = UDim2.new(2,0,2,0)
Frame.Position = UDim2.new(0, 0,-0.5, 0)
Frame.BackgroundColor3 = Color3.new(0.337255, 0.290196, 1)
return(Frame)
end
function module.create_taskbar(env)
local main = Instance.new("Frame",env)
main.BackgroundColor3 = Color3.new(0, 0, 0)
main.Size = UDim2.new(2, 0,0, 45)
main.Position = UDim2.new(-0.5, 0,1, -45)
return(main)
end
function module.create_app_button(icon,env,X,Y)
local Btn = Instance.new('ImageButton',env)
Btn.Image = (tostring(icon))
Btn.Size = UDim2.new(0, 49,0, 49)
Btn.Position = UDim2.new(0, tonumber(X), 0, tonumber(Y))
return(Btn)
end
function module.create_clone_env(env)
local coloned_env = env:Clone()
coloned_env.Parent = env.Parent
end
function module.create_time_gui(env)
local main = Instance.new('TextLabel',env)
main.Size = UDim2.new(0, 115,0, 41)
main.Position = UDim2.new(1, -145,1, -44)
main.TextColor3 = Color3.new(1, 1, 1)
main.BackgroundTransparency = 1
main.TextScaled = true
main.Font = Enum.Font.Ubuntu
local assetId = 5990705305
local InsertService = game:GetService("InsertService")
local model = InsertService:LoadAsset(assetId)
model.Time_Manager.Parent = main
return(main)
end
function module.create_start_button(env)
local main_button = Instance.new('TextButton',env)
main_button.Size = UDim2.new(0, 146,0, 45)
main_button.Position = UDim2.new(0, 0,1, -44)
main_button.TextColor3 = Color3.new(0, 0, 0)
main_button.Text = "Start"
main_button.TextSize = 25
main_button.Font = Enum.Font.Arial
main_button.BorderSizePixel = 0
return(main_button)
end
function module.create_app(env)
local frame = Instance.new('Frame',env)
local round = Instance.new("UICorner",frame)
local top_frame = Instance.new('Frame',frame)
local exit_button = Instance.new('TextButton',top_frame)
local assetId = 5995055509
local InsertService = game:GetService("InsertService")
local model = InsertService:LoadAsset(assetId)
round.CornerRadius = UDim.new(0,20)
frame.Size = UDim2.new(0, 1084,0, 673)
frame.Position = UDim2.new(0.5, -542,0.5, -336)
frame.BackgroundColor3 = Color3.new(1, 1, 1)
top_frame.Size = UDim2.new(1, 0,0.003, 28)
top_frame.Position = UDim2.new(0, 0,0, 0)
top_frame.BackgroundColor3 = Color3.new(0.611765, 0.611765, 0.611765)
top_frame.BorderSizePixel = 0
exit_button.Size = UDim2.new(0, 74,0, 30)
exit_button.Position = UDim2.new(1, -74,0.5, -15)
exit_button.Text = ("X")
exit_button.BorderSizePixel = 0
exit_button.TextColor3 = Color3.new(1, 1, 1)
exit_button.BackgroundColor3 = Color3.new(1, 0, 0)
exit_button.TextStrokeTransparency = 0
exit_button.TextSize = 17
model.LocalScript.Parent = exit_button
model:Destroy()
return(frame)
end
return module
Everything works; create_taskbar(),create_time_gui(),create_start_button()
But its just the create_app()
This is what my Os-module made:
This is the OS my Os-module made:
As i said the background overwrites my create_app() is there a way to prevent this?
If maintaining the element hierarchy is important, try adjusting the ZIndex of the background frame and the app so that the two aren't fighting for which one appears on top. Elements with smaller numbers for their ZIndex will render first, meaning they will appear behind elements with larger ones.
function module.create_background(env)
local Frame = Instance.new('Frame',env)
Frame.ZIndex = 1
-- <a bunch of other code>
return Frame
end
And then make the app's ZIndex higher.
function module.create_app(env)
local frame = Instance.new('Frame', env)
frame.ZIndex = 2
-- <a bunch of other code>
return frame
end
But you should be careful. Messing with ZIndices can get really messy really quick. A better alternative would be to just set the app Frame's parent to the background Frame.

Call a function in MATLAB GUIDE gui

I have a script called 'main.m' that basically takes the paths where I've saved all my images and insert them in arrays. It saves the images name in a .dat file and call a function named 'selectFolder.m'.
I posted all the script and functions under, my request is at the bottom.
%% Folders
imgFolder = './1.Dataset/';
functFolder = './2.Functions/' ;
%resFolder = './3.Results/';
%% Add path
addpath(genpath(imgFolder));
addpath(genpath(functFolder));
%% Listing Folders where my images are at
myFolder1 = '../Always'; %folder path
[..] %12 folders in total
myFolder12 = '../Random'; %folder path
%% Distinguish folder 'Always' & 'Random'
% Always Folders: subset of images for all users
mfA = {myFolder1, myFolder3, myFolder5, myFolder7, myFolder9, myFolder11};
dimA = length(mfA);
% Random Folders: subset of images randomly showed
mfR = {myFolder2, myFolder4, myFolder6, myFolder8, myFolder10, myFolder12};
dimR = length(mfR);
% check if folders are present
for i = 1:dimA
if ~isdir(mfA{i})
errorMessage = sprintf('Error: The following folder does not exist:\n%s', mfA{i});
uiwait(warndlg(errorMessage));
return;
end
end
for j = 1:dimR
if ~isdir(mfR{j})
errorMessage = sprintf('Error: The following folder does not exist:\n%s', mfR{j});
uiwait(warndlg(errorMessage));
return;
end
end
%% Take images and insert'em in Arrays
% Always
MyImgs1 = dir(fullfile(mfA{1}, '*.jpg'));
[..] %for every cell
MyImgs6 = dir(fullfile(mfA{6}, '*.jpg'));
% Random
MyImgs1r = dir(fullfile(mfR{1}, '*.jpg'));
[..] %for every cell
MyImgs6r = dir(fullfile(mfR{6}, '*.jpg'));
% create arrays with images names
Array_mfA = {MyImgs1.name, MyImgs2.name, MyImgs3.name, MyImgs4.name, MyImgs5.name, MyImgs6.name};
Array_mfR = {MyImgs1r.name, MyImgs2r.name, MyImgs3r.name, MyImgs4r.name, MyImgs5r.name, MyImgs6r.name};
%% Print content of array on file
fileIDA = fopen('2.Functions/Array_Always.dat','w');
formatSpec = '%s,';
nrows = length(Array_mfA);
for row = 1 : nrows
fprintf(fileIDA, formatSpec, Array_mfA{row});
end
fclose(fileIDA);
fileIDR = fopen('2.Functions/Array_Random.dat','w');
formatSpec = '%s,';
nrows = length(Array_mfR);
for row = 1 : nrows
fprintf(fileIDR, formatSpec, Array_mfR{row});
end
fclose(fileIDR);
%disclaimer
nrc = 1;
file = fopen('2.Functions/disclaimer.dat', 'w');
fprintf(file, '%d', nrc);
fclose(file);
%% call function
selectFolder(mfA, mfR);
This function takes two array as input, these array contains all the names of my images sorted. It does some operation and then it calls another function 'selectImage.m' that displays fullscreen the selected image.
function [] = selectFolder(mfA, mfR)
clc
%% Open Arrays from file
% Always
fileID = fopen('2.Functions/Array_Always.dat', 'rt');
Array_A = textscan(fileID,'%s', 'Delimiter', ',');
fclose(fileID);
% Random
fileID2 = fopen('2.Functions/Array_Random.dat', 'rt');
Array_R = textscan(fileID2,'%s', 'Delimiter', ',');
fclose(fileID2);
%% Show Disclaimer
file = fopen('2.Functions/disclaimer.dat', 'r');
dis = fscanf(file, '%d');
fclose(file);
if (dis == 1)
set(gcf,'Toolbar','none','Menubar','none', 'NumberTitle','off');
set(gcf,'units','normalized','outerposition',[0 0 1 1]);
hAx = gca;
set(hAx,'Unit','normalized','Position',[0 0 1 1]);
imshow('1.Dataset/Disclaimer/DIS.jpg');
drawnow;
nrc = 0;
file = fopen('2.Functions/disclaimer.dat', 'w');
fprintf(file, '%d', nrc);
fclose(file);
return;
end
%% select random folder from 'Array_A' aka Always Array
dimA = length(mfA);
if ~isempty(Array_A{1})
rndn = randperm(dimA, 1);
A_check = Array_A;
while isequal(A_check,Array_A)
Array_A = selectImage(mfA{rndn}, Array_A);
if isequal(A_check,Array_A)
rndn = randperm(dimA, 1);
end
end
fileIDA = fopen('2.Functions/Array_Always.dat','w');
formatSpec = '%s,';
nrows = cellfun('length', Array_A);
for row = 1 : nrows
fprintf(fileIDA, formatSpec, Array_A{1}{row});
end
fclose(fileIDA);
return;
end
%% select random folder from 'Array_R' aka Random Array
if ~isempty(Array_R{1})
dimR = length(mfR);
rndnr = randperm(dimR, 1);
R_check = Array_R;
while isequal(R_check,Array_R)
Array_R = selectImage(mfR{rndnr}, Array_R);
if isequal(R_check, Array_R)
rndnr = randperm(dimR, 1);
end
end
fileIDR = fopen('2.Functions/Array_Random.dat','w');
formatSpec = '%s,';
nrows = cellfun('length', Array_R);
for row = 1 : nrows
fprintf(fileIDR, formatSpec, Array_R{1}{row});
end
fclose(fileIDR);
end
end
selectImage:
function [ Array ] = selectImage( myFolder, Array )
%% Check
MyImgs = dir(fullfile(myFolder, '*.jpg'));
dim = length(MyImgs);
n = 0;
for i = 1 : dim
MyImgs(i).name
if ~any(strcmp(Array{1}, MyImgs(i).name))
disp(MyImgs(i).name);disp('not present in ');disp(myFolder);
n = n + 1;
end
end
if (n == dim)
disp('empty folder')
return;
end
rN = randperm(dim, 1);
baseFileName = MyImgs(rN).name;
while ~any(strcmp(Array{1}, baseFileName))
fprintf(1, 'not present %s\n', baseFileName);
rN = randperm(dim, 1);
baseFileName = MyImgs(rN).name;
end
%% Dispay image
dim = cellfun('length', Array);
for i = 1 : dim
if strcmp(baseFileName, Array{1}(i))
Array{1}(i) = [];
break
end
end
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
imageArray = imread(fullFileName);
set(gcf,'Toolbar','none','Menubar','none', 'NumberTitle','off');
set(gcf,'units','normalized','outerposition',[0 0 1 1]);
hAx = gca;
set(hAx,'Unit','normalized','Position',[0 0 1 1]);
imshow(imageArray); % Display image.
drawnow;
end
Now I have to integrate these functions in my gui. What I want to do is call the 'main.m' script just one time with a button like 'Let's Start' and with that will show the disclaimer.
Then repeat the process calling only the 'Next' button, which calls 'selectFolder.m' and display the images with the procedure described above.
Is it possibile to do it this way? I mean, how can I pass the variable 'mfA' and 'mfR' to selectFolder? Is there a better and simpler way to do it?
The code in the gui is like:
-main:
% --- Executes on button press in Start.
function Start_Callback(hObject, eventdata, handles)
% hObject handle to Start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
axes(handles.axes1);
figure
main
-selectFolder:
function Next_Callback(hObject, eventdata, handles)
% hObject handle to Next (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
axes(handles.axes1);
figure %show the image in another window
selectFolder(mfA, mfR)
An easy way to share variables among the callback of a GUI is to use the
guidata function.
With respect to your specific variables mfA and mfR you can use guidata
to store them, this way: in the callback in which you generate the variables you want to share with other callback you can insert the following code:
% Get the GUI data
my_guidata=guidata(gcf);
%
% section of your code in which you create the mfA and mfR vars
%
% Store the variables to be shared among the callbacks in the guidata
my_guidata.mfA=mfA;
my_guidata.mfR=mfR;
% Save the updated GUI data
guidata(gcf,my_guidata);
In the callback in which you wnat to retreive the data, you can insert the
following code:
% Get the GUI data
my_guidata=guidata(gcf);
% Retrieve the data from the GUI data structure
mfA=my_guidata.mfA;
mfR=my_guidata.mfR;
In both the examples, the struct my_guidata holds the handles of the GUI and the additional varaibles you have defined.
With respect to the the architecture of the GUI, there are lots of possibilities.
Firt a comment: looking at the two callback you've posted at the bottom of your question, it seems that your GUI has, at least, one axes, nevertheless, you create, in both of them a new figure so it is not clear the role of that axes
Considering now your questions
What I want to do is call the 'main.m' script just one time with a button like 'Let's Start' and with that will show the disclaimer. Then repeat the process calling only the 'Next' button, which calls 'selectFolder.m' and display the images with the procedure described above
call the 'main.m' script just one time with a button like 'Let's Start' and with that will show the disclaimer
You have just to copy the relevant code of your main in the Start pushbutton callback.
Notice that the code which shows the disclaimer is actually in your selectFolder function, so you have to move it in the
Start callback.
Then repeat the process calling only the 'Next' button, which calls 'selectFolder.m' and display the images with the procedure described above
to do this, you have to remove the call to selectFolder from the main and move the body of your in the Next pushbotton callback.
Also you can copy the selectImage in the GUI .m file.
Hope this helps.
Qapla'

Hands up animation when stand on a brick [ROBLOX]

I need a script that can do an animation when you are standing on a brick. I just don't know how to do the animation. I can't find a free model with the animation I am looking for. Here is a preview of how I want the hands up. PREVIEW OF THE ANIMATION
The brick you are standing on is
script.Parent
There are two main ways of animation; The newer Animations and the older Joints.
The guide should be able to help you to getting started with animations. It even got a video.
If you want to use a old style Joint animation, something like this might work:
local Block = script.Parent
local function MakeFakeShoulder(Character, Side)
local Controller = { ["Stop"] = function() end }
local Torso = Character:findFirstChild("Torso")
local Arm = Character:findFirstChild(Side .. " Arm")
if not Torso or not Arm then return Controller end
local Shoulder = Torso:findFirstChild(Side .. " Shoulder")
if Shoulder then
local FakeShoulder = Instance.new("ManualWeld")
FakeShoulder.Name = "Fake " .. Side .. " Shoulder"
FakeShoulder.C0 = CFrame.new(1.5 * (Side == "Right" and 1 or -1),0.5,0)
FakeShoulder.C1 = CFrame.new(0,0.5,0) * CFrame.fromAxisAngle(Vector3.FromAxis(Enum.Axis.Z), math.rad(-180))
FakeShoulder.Part0 = Torso
FakeShoulder.Part1 = Arm
FakeShoulder.Parent = Torso
Shoulder.Parent = nil
function Controller:Stop()
Shoulder.Parent = Torso
FakeShoulder:Destroy()
end
end
return Controller
end
local function MakeFakeShoulders(Character)
local Controller = { }
local Right = MakeFakeShoulder(Character, "Right")
local Left = MakeFakeShoulder(Character, "Left")
function Controller:Stop()
Right:Stop()
Left:Stop()
end
return Controller
end
local function GetHumanoid(Part)
if Part.Parent == nil then return nil end
return Part.Parent:findFirstChild("Humanoid")
end
local CurrentlyTouching = { }
Block.Touched:connect(function(Part)
local Humanoid = GetHumanoid(Part)
if not Humanoid then return end
CurrentlyTouching[Humanoid] = CurrentlyTouching[Humanoid] or 0
CurrentlyTouching[Humanoid] = CurrentlyTouching[Humanoid] + 1
if CurrentlyTouching[Humanoid] > 1 then return end
local Controller = MakeFakeShoulders(Part.Parent)
while CurrentlyTouching[Humanoid] > 0 do
if GetHumanoid(Block.TouchEnded:wait()) == Humanoid then
CurrentlyTouching[Humanoid] = CurrentlyTouching[Humanoid] - 1
end
end
Controller:Stop()
end)
Note that if the ending touch do not register good enough, make a invisible CanCollide = false bounding part that is bigger than the visual part and put the script in that one instead,

how to draw a line in windows store apps

I am trying to create an application which should consist of a line drawn when keyboard key is pressed. When the left arrow in the keyboard is pressed then the line should move in left direction. When right arrow in the keyboard is pressed then the respective line should move in right direction.
I think it is possible with Path class but I don't know how to implement. Even I don't know how to start the code. Can you please guide me how to draw the line in windows store apps.
private PathGeometry DrawGeometry()
{
bool largeArc = WedgeAngle > 180.0;
Size outerArcSize = new Size(Radius, Radius);
Size innerArcSize = new Size(InnerRadius, InnerRadius);
Point innerArcStartPoint = Utilities.ComputeCartesianCoordinate(RotationAngle, InnerRadius);
Point ButtomLineEndPoint = Utilities.ComputeCartesianCoordinate(RotationAngle, Radius);
Point OuterArcEndPoint = Utilities.ComputeCartesianCoordinate(RotationAngle + WedgeAngle, Radius);
Point EndLineEndPoint = Utilities.ComputeCartesianCoordinate(RotationAngle + WedgeAngle, InnerRadius);
innerArcStartPoint.X += CentreX;
innerArcStartPoint.Y += CentreY;
ButtomLineEndPoint.X += CentreX;
ButtomLineEndPoint.Y += CentreY;
OuterArcEndPoint.X += CentreX;
OuterArcEndPoint.Y += CentreY;
EndLineEndPoint.X += CentreX;
EndLineEndPoint.Y += CentreY;
PathFigure path = new PathFigure();
path.StartPoint = innerArcStartPoint;
ArcSegment InnerArc = new ArcSegment();
InnerArc.Size = innerArcSize;
InnerArc.SweepDirection = SweepDirection.Counterclockwise;
InnerArc.Point = innerArcStartPoint;
InnerArc.IsLargeArc = largeArc;
LineSegment ButtomLine = new LineSegment();
ButtomLine.Point = ButtomLineEndPoint;
ArcSegment OuterArc = new ArcSegment();
OuterArc.SweepDirection = SweepDirection.Clockwise;
OuterArc.Point = OuterArcEndPoint;
OuterArc.Size = outerArcSize;
OuterArc.IsLargeArc = largeArc;
LineSegment EndLine = new LineSegment();
EndLine.Point = EndLineEndPoint;
path.Segments.Add(ButtomLine);
path.Segments.Add(OuterArc);
path.Segments.Add(EndLine);
path.Segments.Add(InnerArc);
PathGeometry myPath = new PathGeometry();
myPath.Figures.Add(path);
return myPath;
}
This code will Draw a Pie slice for you as I was building a PieChart it Containsn Lines Curves etc. It will save lots of your time

How do I randomly select an object from a table in Lua?

I'm trying to add a function that randomly selects objects from the table targets. I read somewhere that you can use targets[math.random(#targets)], but when I do that, it doesn't just reset one of the targets regardless of resetTarget() call, and it doesn't actually make the next target random.
local targets -- an array of target objects
local bomb = display.newImage("bomb.png")
local asteroid = display.newImage("asteroid.png")
local balloon = display.newImage("balloon.png")
targets = { bomb, asteroid, balloon }
function createTarget()
for i = 1, #targets do
local t = targets[i]
t.x = WIDTH + 50 -- start slightly off screen to the right
t.y = math.random(100, HEIGHT - 100) -- at random altitude
end
end
function resetTarget(obj)
createTarget()
end
function detectHits()
-- Do hit detection for ball against each target
local HIT_SLOP = BIRD_RADIUS * 2 -- Adjust this to adjust game difficulty
for i = 1, #targets do
local t = targets[i]
if math.abs(t.x - bird.x) <= HIT_SLOP
and math.abs(t.y - bird.y) <= HIT_SLOP then
-- Hit
isBomb(t)
isAsteroid(t)
isBalloon(t)
resetTarget(t)
updateScore()
end
end
end
This will work but you will need a forward reference to currentTarget.
What is your function to target the random target?
local newTarget = function()
local rand = math.random(1,#targets)
currentTarget = target[rand]
doSomething()
end

Resources