Шукати в цьому блозі

форум 8

 *
ЗНАЙТИ ПЕРЕТИН ДВОХ ВІДРІЗКІВ(функція)
Код:: [ Скачать ] [ Скрыть ] [ Свернуть ]
Синтаксис: Lua
------------
-- ЗНАЙТИ ПЕРЕТИН  ДВОХ ВІДРІЗКІВ
----------------
function perehrest(x1,y1,x2,y2,x3,y3,x4,y4)  --  пересікання 2 відрізків

        if x1 > x2 then  x1,x2,y1,y2=x2,x1,y2,y1    end
        if x3 > x4 then  x3,x4,y3,y4=x4,x3,y4,y3   end
       
       
       
        if  y2 == y1  then      k1 = 0  else k1 =  ( y2 - y1 ) / ( x2 - x1 )    end
        if y3 == y4 then k2 = 0 else  k2 =  ( y4 - y3 ) / ( x4 - x3 ) end
       
        if k1 == k2 then
                print(" прямые параллельны и отрезки пересекаться не могут")
        else
       

                if (x1<=x4 and x4<= x2) or (x1<=x3 and x3<=x2 ) then
                        print("перетин  в межах відрізку")
               
                       
                end

                        b1 = y1 - k1 * x1
                        b2 = y3  - k2 * x3

                        --точка перетину x,y
                        x = ( b2 - b1 ) / ( k1 -  k2 )
                        y = k1*+ b1
                        print("точка перетину"..x, y)
               
        end




end


perehrest(10,10,100,100,10,100,100,10)

_________________

Learn Lua in 15 Minutes
Код:: [ Скачать ] [ Скрыть ] [ Свернуть ]
Синтаксис: Lua

-- Two dashes start a one-line comment.

--[[
     Adding two ['s and ]'s makes it a
     multi-line comment.
--]]


----------------------------------------------------
-- 1. Variables and flow control.
----------------------------------------------------

num = 42  -- All numbers are doubles.
-- Don't freak out, 64-bit doubles have 52 bits for
-- storing exact int values; machine precision is
-- not a problem for ints that need < 52 bits.

= 'walternate'  -- Immutable strings like Python.
= "double-quotes are also fine"
= [[ Double brackets
       start and end
       multi-line strings.]]
= nil  -- Undefines t; Lua has garbage collection.

-- Blocks are denoted with keywords like do/end:
while num < 50 do
  num = num + 1  -- No ++ or += type operators.
end

-- If clauses:
if num > 40 then
  print('over 40')
elseif s ~= 'walternate' then  -- ~= is not equals.
  -- Equality check is == like Python; ok for strs.
  io.write('not over 40\n')  -- Defaults to stdout.
else
  -- Variables are global by default.
  thisIsGlobal = 5  -- Camel case is common.

  -- How to make a variable local:
  local line = io.read()  -- Reads next stdin line.

  -- String concatenation uses the .. operator:
  print('Winter is coming, ' .. line)
end

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

aBoolValue = false

-- Only nil and false are falsy; 0 and '' are true!
if not aBoolValue then print('twas false') end

-- 'or' and 'and' are short-circuited.
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --> 'no'

karlSum = 0
for i = 1, 100 do  -- The range includes both ends.
  karlSum = karlSum + i
end

-- Use "100, 1, -1" as the range to count down:
fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end

-- In general, the range is begin, end[, step].

-- Another loop construct:
repeat
  print('the way of the future')
  num = num - 1
until num == 0


----------------------------------------------------
-- 2. Functions.
----------------------------------------------------

function fib(n)
  if n < 2 then return 1 end
  return fib(- 2) + fib(- 1)
end

-- Closures and anonymous functions are ok:
function adder(x)
  -- The returned function is created when adder is
  -- called, and remembers the value of x:
  return function (y) return x + y end
end
a1 = adder(9)
a2 = adder(36)
print(a1(16))  --> 25
print(a2(64))  --> 100

-- Returns, func calls, and assignments all work
-- with lists that may be mismatched in length.
-- Unmatched receivers are nil;
-- unmatched senders are discarded.

x, y, z = 1, 2, 3, 4
-- Now x = 1, y = 2, z = 3, and 4 is thrown away.

function bar(a, b, c)
  print(a, b, c)
  return 4, 8, 15, 16, 23, 42
end

x, y = bar('zaphod')  --> prints "zaphod  nil nil"
-- Now x = 4, y = 8, values 15..42 are discarded.

-- Functions are first-class, may be local/global.
-- These are the same:
function f(x) return x * x end
= function (x) return x * x end

-- And so are these:
local function g(x) return math.sin(x) end
local g; g  = function (x) return math.sin(x) end
-- the 'local g' decl makes g-self-references ok.

-- Trig funcs work in radians, by the way.

-- Calls with one string param don't need parens:
print 'hello'  -- Works fine.


----------------------------------------------------
-- 3. Tables.
----------------------------------------------------

-- Tables = Lua's only compound data structure;
--          they are associative arrays.
-- Similar to php arrays or js objects, they are
-- hash-lookup dicts that can also be used as lists.

-- Using tables as dictionaries / maps:

-- Dict literals have string keys by default:
= {key1 = 'value1', key2 = false}

-- String keys can use js-like dot notation:
print(t.key1)  -- Prints 'value1'.
t.newKey = {}  -- Adds a new key/value pair.
t.key2 = nil   -- Removes key2 from the table.

-- Literal notation for any (non-nil) value as key:
= {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
print(u[6.28])  -- prints "tau"

-- Key matching is basically by value for numbers
-- and strings, but by identity for tables.
= u['@!#']  -- Now a = 'qbert'.
= u[{}]     -- We might expect 1729, but it's nil:
-- b = nil since the lookup fails. It fails
-- because the key we used is not the same object
-- as the one used to store the original value. So
-- strings & numbers are more portable keys.

-- A one-table-param function call needs no parens:
function h(x) print(x.key1) end
h{key1 = 'Sonmi~451'}  -- Prints 'Sonmi~451'.

for key, val in pairs(u) do  -- Table iteration.
  print(key, val)
end

-- _G is a special table of all globals.
print(_G['_G'] == _G)  -- Prints 'true'.

-- Using tables as lists / arrays:

-- List literals implicitly set up int keys:
= {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #do  -- #v is the size of v for lists.
  print(v[i])  -- Indices start at 1 !! SO CRAZY!
end
-- A 'list' is not a real type. v is just a table
-- with consecutive integer keys, treated as a list.

----------------------------------------------------
-- 3.1 Metatables and metamethods.
----------------------------------------------------

-- A table can have a metatable that gives the table
-- operator-overloadish behavior. Later we'll see
-- how metatables support js-prototypey behavior.

f1 = {= 1, b = 2}  -- Represents the fraction a/b.
f2 = {= 2, b = 3}

-- This would fail:
-- s = f1 + f2

metafraction = {}
function metafraction.__add(f1, f2)
  sum = {}
  sum.= f1.* f2.b
  sum.= f1.* f2.+ f2.* f1.b
  return sum
end

setmetatable(f1, metafraction)
setmetatable(f2, metafraction)

= f1 + f2  -- call __add(f1, f2) on f1's metatable

-- f1, f2 have no key for their metatable, unlike
-- prototypes in js, so you must retrieve it as in
-- getmetatable(f1). The metatable is a normal table
-- with keys that Lua knows about, like __add.

-- But the next line fails since s has no metatable:
-- t = s + s
-- Class-like patterns given below would fix this.

-- An __index on a metatable overloads dot lookups:
defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal  -- works! thanks, metatable

-- Direct table lookups that fail will retry using
-- the metatable's __index value, and this recurses.

-- An __index value can also be a function(tbl, key)
-- for more customized lookups.

-- Values of __index,add, .. are called metamethods.
-- Full list. Here a is a table with the metamethod.

-- __add(a, b)                     for a + b
-- __sub(a, b)                     for a - b
-- __mul(a, b)                     for a * b
-- __div(a, b)                     for a / b
-- __mod(a, b)                     for a % b
-- __pow(a, b)                     for a ^ b
-- __unm(a)                        for -a
-- __concat(a, b)                  for a .. b
-- __len(a)                        for #a
-- __eq(a, b)                      for a == b
-- __lt(a, b)                      for a < b
-- __le(a, b)                      for a <= b
-- __index(a, b)    for a.b
-- __newindex(a, b, c)             for a.b = c
-- __call(a, ...)                  for a(...)

----------------------------------------------------
-- 3.2 Class-like tables and inheritance.
----------------------------------------------------

-- Classes aren't built in; there are different ways
-- to make them using tables and metatables.

-- Explanation for this example is below it.

Dog = {}                                   -- 1.

function Dog:new()                         -- 2.
  newObj = {sound = 'woof'}                -- 3.
  self.__index = self                      -- 4.
  return setmetatable(newObj, self)        -- 5.
end

function Dog:makeSound()                   -- 6.
  print('I say ' .. self.sound)
end

mrDog = Dog:new()                          -- 7.
mrDog:makeSound()  -- 'I say woof'         -- 8.

-- 1. Dog acts like a class; it's really a table.
-- 2. function tablename:fn(...) is the same as
--    function tablename.fn(self, ...)
--    The : just adds a first arg called self.
--    Read 7 & 8 below for how self gets its value.
-- 3. newObj will be an instance of class Dog.
-- 4. self = the class being instantiated. Often
--    self = Dog, but inheritance can change it.
--    newObj gets self's functions when we set both
--    newObj's metatable and self's __index to self.
-- 5. Reminder: setmetatable returns its first arg.
-- 6. The : works as in 2, but this time we expect
--    self to be an instance instead of a class.
-- 7. Same as Dog.new(Dog), so self = Dog in new().
-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.

----------------------------------------------------

-- Inheritance example:

LoudDog = Dog:new()                           -- 1.

function LoudDog:makeSound()
  s = self.sound .. ' '                       -- 2.
  print(.. s .. s)
end

seymour = LoudDog:new()                       -- 3.
seymour:makeSound()  -- 'woof woof woof'      -- 4.

-- 1. LoudDog gets Dog's methods and variables.
-- 2. self has a 'sound' key from new(), see 3.
-- 3. Same as LoudDog.new(LoudDog), and converted to
--    Dog.new(LoudDog) as LoudDog has no 'new' key,
--    but does have __index = Dog on its metatable.
--    Result: seymour's metatable is LoudDog, and
--    LoudDog.__index = LoudDog. So seymour.key will
--    = seymour.key, LoudDog.key, Dog.key, whichever
--    table is the first with the given key.
-- 4. The 'makeSound' key is found in LoudDog; this
--    is the same as LoudDog.makeSound(seymour).

-- If needed, a subclass's new() is like the base's:
function LoudDog:new()
  newObj = {}
  -- set up newObj
  self.__index = self
  return setmetatable(newObj, self)
end

----------------------------------------------------
-- 4. Modules.
----------------------------------------------------


--[[ I'm commenting out this section so the rest of
--   this script remains runnable.
-- Suppose the file mod.lua looks like this:
local M = {}

local function sayMyName()
  print('Hrunkner')
end

function M.sayHello()
  print('Why hello there')
  sayMyName()
end

return M

-- Another file can use mod.lua's functionality:
local mod = require('mod')  -- Run the file mod.lua.

-- require is the standard way to include modules.
-- require acts like:     (if not cached; see below)
local mod = (function ()
 
end)()
-- It's like mod.lua is a function body, so that
-- locals inside mod.lua are invisible outside it.

-- This works because mod here = M in mod.lua:
mod.sayHello()  -- Says hello to Hrunkner.

-- This is wrong; sayMyName only exists in mod.lua:
mod.sayMyName()  -- error

-- require's return values are cached so a file is
-- run at most once, even when require'd many times.

-- Suppose mod2.lua contains "print('Hi!')".
local a = require('mod2')  -- Prints Hi!
local b = require('mod2')  -- Doesn't print; a=b.

-- dofile is like require without caching:
dofile('mod2.lua')  --> Hi!
dofile('mod2.lua')  --> Hi! (runs it again)

-- loadfile loads a lua file but doesn't run it yet.
f = loadfile('mod2.lua')  -- Call f() to run it.

-- loadstring is loadfile for strings.
g = loadstring('print(343)')  -- Returns a function.
g()  -- Prints out 343; nothing printed before now.

--]]


----------------------------------------------------
-- 5. References.
----------------------------------------------------

--[[

I was excited to learn Lua so I could make games
with the Löve 2D game engine. That's the why.

I started with BlackBulletIV's Lua for programmers.
Next I read the official Programming in Lua book.
That's the how.

It might be helpful to check out the Lua short
reference on lua-users.org.

The main topics not covered are standard libraries:
 * string library
 * table library
 * math library
 * io library
 * os library

By the way, this entire file is valid Lua; save it
as learn.lua and run it with "lua learn.lua" !

This was first written for tylerneylon.com. It's
also available as a github gist. Tutorials for other
languages, in the same style as this one, are here:

http://learnxinyminutes.com/

Have fun with Lua!

--]]

 

________

генератор вибухів
http://explosiongenerator.com/

_________________

все апі Gideros, автоматично генерується після кожного оновлення

https://www.dropbox.com/s/62dtqjtfqsbl2 ... i.pdf?dl=0

_________________

Код:: [ Скачать ] [ Скрыть ] [ Свернуть ]
Синтаксис: Lua
--[[
клас Масштабування жестом
v.1.0
(c) https://www.facebook.com/AndroidMobileGame
ВИКОРИСТАННЯ:
------------------------------------

        local Sprite1=Lupa.new()
        stage:addChild(Sprite1)


-------------------------------------
]]


Lupa = gideros.class(Sprite)

function Lupa:init(mode)
         if mode then
                self.m=mode
         else
                self.m=2
         end
        self:addEventListener(Event.TOUCHES_BEGIN, self.onTouchesBegin, self)
        self:addEventListener(Event.TOUCHES_MOVE, self.onTouchesMove, self)
        self:addEventListener(Event.TOUCHES_END, self.onTouchesEnd, self)
        self:addEventListener(Event.TOUCHES_CANCEL, self.onTouchesEnd, self)
       
end



 function Lupa:onTouchesBegin(event)
        if event.touch.id==1 then
                self.startY=event.touch.y
                self.startX=event.touch.x
        elseif event.touch.id==2 then
                self.startY2=event.touch.y
                self.startX2=event.touch.x
                self.on=true
        end

end

 function Lupa:onTouchesMove(event)

        if event.touch.id==1 then

                -- ПЕРЕМІЩЕННЯ 1
                if (self.m==1 and self.startX) or   (self.m>1 and self.on and self.startX) then
                        self:setPosition(self:getX()+event.touch.x-self.startX,self:getY()+event.touch.y-self.startY)
               
                end
               
                self.startY=event.touch.y
                self.startX=event.touch.x

                --------------------------------
                --встановити якір на палець 1
                --------------------------------
                if self.on then
                        local  s=self:getScale() --масштаб
                        local ax,ay=self:getAnchorPosition()  --старі координати якоря  
                        --поправка на масштаб
                        ax=ax*s
                        ay=ay*s
                        local px,py=self:getPosition() -- координати спрайта
                        --найти верхній лівий край 
                        local kx=px-ax
                        local ky=py-ay
                       
                        local cy= self.startY
                        local cx= self.startX
                       
                       
                        -- новий якір
                        local ax2=cx-kx  
                        local ay2=cy-ky          
                        self:setAnchorPosition(ax2/s,ay2/s) --встановити новий якір s-поправка на масштаб
                        self:setPosition(px+(ax2-ax),py+(ay2-ay)) -- коригувати позицію спрайту згідно нового якоря
                       
                end
                ----------------------------------

        elseif event.touch.id==2 then

                self.startY2=event.touch.y
                self.startX2=event.touch.x
                ----------------------------------
                -- дистанція між пальцем 1 і 2 
                if self.on then
                        self.d2= math.sqrt((self.startX-event.touch.x)^2+(self.startY-event.touch.y)^2) 
                        if self.then
                                 self:setScale(self:getScaleX()*( self.d2/self.d))   -- масштаб
                        end
                        self.d=self.d2
                end
                ----------------------------------
        end

       
end

 function Lupa:onTouchesEnd(event)
        --ВИМКНУТИ ЯКЩО 1 ПАЛЕЦЬ ВІДПУСТИТИ
        if event.touch.id==1 or event.touch.id==2 then
                self.on=nil
                self.d=nil
                self.startY=nil
                self.startX=nil
        end
end

 

_________________

Код:: [ Скачать ] [ Скрыть ] [ Свернуть ]
Синтаксис: Lua
--[[
клас кнопки
ВИКОРИСТАННЯ:
------------------------------------

        local score=Bitmap.new(Texture.new("img/gui_70.png"))
        score:setAnchorPoint(0.5, 0)
        score:setPosition(halfWidth, miny)
        self:addChild(score)
       
        local pause = Button.new(Bitmap.new(Texture.new("img/gui_48.png")))
        stage:addChild(pause)


        pause:addEventListener("clickDown",
                function(e)    
                e:stopPropagation()
                        knopka:play()
                end)
               
        pause:addEventListener("clickUP",
                function(e)    
                e:stopPropagation()
                        knopka:play()
                       
                end)   
                pause:addEventListener("clickMove",
                function(e)    
                print(e.x)
                       
                       
                end)   
-------------------------------------
]]


Button = gideros.class(Sprite)

function Button:init(upState)
        self:addChild(upState)
        self:addEventListener(Event.TOUCHES_BEGIN, self.onTouchesBegin, self)
        self:addEventListener(Event.TOUCHES_MOVE, self.onTouchesMove, self)
        self:addEventListener(Event.TOUCHES_END, self.onTouchesEnd, self)
        self.on=false
end



 function Button:onTouchesBegin(event)

        if self:hitTestPoint(event.touch.x, event.touch.y) then
       
                if event.touch.id~=self.focus then
                        self.focus=event.touch.id
                       
                        if self.on==false then
                       
                               
                                self:dispatchEvent(Event.new("clickDown"))
                                self.on=true
                                self:setColorTransform(2, 2, 2, 1)
                        end
                        --print("natysnuv"..event.touch.id)
                end
                event:stopPropagation()
        end

end

 function Button:onTouchesMove(event)
        if self:hitTestPoint(event.touch.x, event.touch.y) then
       
                if self.focus~=event.touch.id then
                        self.focus=event.touch.id
                       
                       
                       
                        if self.on==false then
                               
                                self:dispatchEvent(Event.new("clickDown"))
                                self.on=true
                                self:setColorTransform(2, 2, 2, 1)
                                --print("naviv"..event.touch.id)
                       
                                       
                        end
                else
                                       
                                        local clickMove = Event.new("clickMove")
                                        clickMove.= event.touch.x
                                        clickMove.= event.touch.y
                                        self:dispatchEvent(clickMove)
                end
        --event:stopPropagation()
        elseif self.focus==event.touch.id then
                --print("vidviv"..event.touch.id)
                self.focus=nil
                if self.on==true then
                        self.on=false
                        self:setColorTransform(1, 1, 1, 1)
                end
                event:stopPropagation()
        end
       
end

 function Button:onTouchesEnd(event)
        if self:hitTestPoint(event.touch.x, event.touch.y) then
       
                self.focus=nil
               
                if self.on==true then
                       
                        self.on=false
                        self:setColorTransform(1, 1, 1, 1)
                        self:dispatchEvent(Event.new("clickUP"))
                        --print("vidtysnuv"..event.touch.id)
                end
                --event:stopPropagation()
        end
       
end


 

_________________

[2016.10] Sprite:setBlendMode(src, dst)

Gideros підтримує 121 варіант накладання(змішування) малюнків аналогічних накладанню в фотошоп

ствоюється накладання командою Sprite:setBlendMode(src, dst)


Існує 11 типів змішування:
    Sprite.ZERO,
    Sprite.ONE,
    Sprite.SRC_COLOR,
    Sprite.ONE_MINUS_SRC_COLOR,
    Sprite.DST_COLOR,
    Sprite.ONE_MINUS_DST_COLOR,
    Sprite.SRC_ALPHA,
    Sprite.ONE_MINUS_SRC_ALPHA,
    Sprite.DST_ALPHA,
    Sprite.ONE_MINUS_DST_ALPHA,
    Sprite.SRC_ALPHA_SATURATE

Комбінуючи їх ми отримуємо 11 * 11 = 121 варіант накладань малюнків:)

Щоб простіше було визначити яке накладання вами потрібно, створений сніпет який генерує таблицю всіх варіантів накладань малюнка

Код:: [ Скачать ] [ Скрыть ] [ Свернуть ]
Синтаксис: Lua
local topTex = Texture.new("top.png",true)
local btmTex = Texture.new("btm.png",true)

lh @ 10 -- label height

local w = (application:getDeviceWidth() - lh) / 11
local h = (application:getDeviceHeight() - lh) / 11
local s = math.min(w, h)

for x = 1, 11 do
        for y = 1, 11 do
                local top = Pixel.new(topTex, s, s)
                local btm = Pixel.new(btmTex, s, s)
                stage:addChild(btm)
                btm:addChild(top)
                btm:setBlendMode(x, y)
                btm:setPosition(lh + s * (x-1), lh + s * (y-1))
        end
end

local t = {}
for k,in pairs(Sprite) do
        if tonumber(v) == v then t[v] = k end
end

for n = 1, 11 do
        local label = TextField.new(nil, t[n], "|")
        label:setX(lh + (n-1) * s + 2)
        label:setY(1)
        label:setClip(0, 0, s - 2, lh)
        stage:addChild(label)
        local line = Pixel.new(0x666666, 1, 1, lh + 11*s)
        line:setX(lh + n * s)
        stage:addChild(line)
end

for n = 1, 11 do
        local label = TextField.new(nil, t[n], "|")
        label:setY(lh + (n-0) * s - 2)
        label:setX(1)
        label:setRotation(-90)
        label:setClip(0, 0, s - 2, lh)
        stage:addChild(label)
        local line = Pixel.new(0x666666, 1, lh + 11*s, 1)
        line:setY(lh + n * s)
        stage:addChild(line)
end

Вкладення:
dfb777735c739b74a24f19998914bd.png
dfb777735c739b74a24f19998914bd.png [ 278.42 КБ | Просмотров: 6 ] 

_________________

Хвилі синусоїди

формула1

 ! 
cy= висота/2
cW=кількість хвиль
cx=ширина
i=крок

(cy/2)*(1-sin(i*cW*3.14/(cx-1)))))



формула2
Код:: [ Скачать ] [ Скрыть ]
Синтаксис: Lua
scale=5  --висота хвилі
speed=20 -- швидкість або ширина хвилі
posY=100  --позиція спрайту
zdvyg=0 -- здвиг хвилі
sprite:setY(scale*math.sin(e.time*speed+zdvyg)+posY)

_________________

Код:: [ Скачать ] [ Скрыть ] [ Свернуть ]
Синтаксис: Lua
-- VirtualRelativeJoystick for Gideros
--
-- Onscreen joystick that only appears when lower left quadrant
-- of screen is touched
--

VirtualRelativeJoystick = Core.class(Sprite)

function VirtualRelativeJoystick:init(options)
  -- default options
  self.= 100
  self.= 100
  self.outerRadius = 100
  self.padColor = 0xaaaadd
  self.knobColor = 0xaaddaa
  self.onPressed = nil
  self.onDragged = nil
  self.onReleased = nil

  self.left = false

  self.xpos = 0
  self.ypos = 0
  self.strength = 0
  self.angle = 0

  self.enabled = false

  -- set user supplied options
  if options then
    for key, value in pairs(options) do
      self[key]= value
    end
  end

  self.outerCircle = self:getNewCircle(self.outerRadius, self.padColor, false)
  self:addChild(self.outerCircle)

  self.innerNubbin = self:getNewCircle(self.outerRadius * .5, self.knobColor, true)
  self:addChild(self.innerNubbin)

  self:setPosition(self.x, self.y)
  self:setVisible(false)

  self:addEventListener(Event.TOUCHES_BEGIN, self.onTouchesBegin, self)
  self:addEventListener(Event.TOUCHES_MOVE, self.onTouchesMove, self)
  self:addEventListener(Event.TOUCHES_END, self.onTouchesEnd, self)
end

--
function VirtualRelativeJoystick:onTouchesCancel(e)
  self:onTouchesEnd(e)
end

--
function VirtualRelativeJoystick:onTouchesBegin(e)
  local tx, ty = e.touch.x, e.touch.y
  local mx, my = application:getContentWidth() * 0.5, application:getContentHeight() * 0.5

  if self.left then
    if tx > mx or ty < my then return end
  else
    if tx < mx or ty < my then return end
  end

  self.controlTouchId = e.touch.id
  self:setPosition(tx, ty)
  self:setVisible(true)
  self.enabled = true -- enable control

  if self.onPressed then
    self.onPressed()
  end -- run code

  e:stopPropagation()
end

--
function VirtualRelativeJoystick:onTouchesMove(e)
  local cos, sin, sqrt, atan2 = math.cos, math.sin, math.sqrt, math.atan2
  if not self.enabled then return end
  if e.touch.id == self.controlTouchId then
    local x, y = self:globalToLocal(e.touch.x, e.touch.y)
    local radius = self.outerRadius
    local distance = sqrt(* x + y * y) >< radius -- limit distance to outer radius
    -- normalized strength for use with angle
    local strength = (distance >< radius) / radius
    local angle = ^>atan2(y, x) + 90

    local ra = ^< self.angle
    y = -distance * cos(ra)
    x = distance * sin(ra)
    self.innerNubbin:setPosition(x, y)

    self.xpos, self.ypos = x / radius, -/ radius

    if self.onPressed then
      self.onDragged(angle, distance, strength) -- run code
    end

        self.angle, self.distance, self.strength = angle, distance, strength

    e:stopPropagation()
  end
end

--
function VirtualRelativeJoystick:onTouchesEnd(e)
  if not self.enabled then return end
  if e.touch.id == self.controlTouchId then
    self.innerNubbin:setPosition(0, 0)
    self.xpos, self.ypos = 0, 0
    self:setVisible(false)

    self.enabled = false
    if self.onReleased then
      self.onReleased() -- run code
    end

    e:stopPropagation()
  end
  self.controlTouchId = nil
end

--
function VirtualRelativeJoystick:getNewCircle(r, color, fill)
  local p = Path2D.new()
  p:setSvgPath(("M %s 0 a %s %s 0 0 0 %s 0 a %s %s 0 0 0 %s 0 Z"):format(-r, r, r, 2 * r, r, r, -2 * r))
  p:setLineThickness(10) -- Outline width
  p:setFillColor(color, fill and .6 or .0) --Fill color
  p:setLineColor(color, .6) --Line color
  return p
end
 

_________________


*

Немає коментарів:

Дописати коментар