PicoPicoGameEngine

Quick Links

ピコピココード

g=ppgraph
pos=pppoint

sc=ppscreen
Bw=sc:size().width
Bh=sc:size().height

sqrt=math.sqrt
floor=math.floor

draw=function(s,c)
local p
for i=1,#s.p do
p=s.p[i]
g:line(
  s.v[p[1]],
  s.v[p[2]],c)
end
end

function add(a,b,r)
 local v
 v=pos()
 v.x=a.x+b.x*r
 v.y=a.y+b.y*r
 return v
end

function sub(a,b)
return add(a,b,-1)
end

function nml(p)
local q=pos()
local l
l=p.x*p.x+p.y*p.y
l=sqrt(l)
q.x=p.x/l
q.y=p.y/l
return q
end

function dot(a,b)
local q=pos()
q.x=a.x*b.x
q.y=a.y*b.y
local r
r=q.x+q.y
return r
end

function len(a,b)
local dx=a.x-b.x
local dy=a.y-b.y
return dx*dx+dy*dy
end

cross=function(s,t,ans)
local function
cross(a,b,c,d)
local t,n1,n2,u,ab
t=sub(b,a)
ab=t
n1=nml(t)
t=sub(d,c)
n2=nml(t)
w1=dot(n1,n2)
w2=1-w1*w1
u=sub(c,a)
local d1,d2
d1=dot(u,n1)-dot(u,n2)*w1
d1=d1/w2
local aa=pos()
aa.x=a.x+n1.x*d1
aa.y=a.y+n1.y*d1
local h=pos(aa)
aa.x=aa.x-a.x
aa.y=aa.y-a.y
l2=ab.x*ab.x+ab.y*ab.y
d1=dot(aa,ab)
if d1>=0 and d1<l2 then
return h
end
end
local a,b
local v,w,z
v=s.v
for i=1,#s.p do
a=s.p[i]
w=t.v
for j=1,#t.p do
b=t.p[j]
z=cross(v[a[1]],v[a[2]],
        w[b[1]],w[b[2]])
if z then
ans[#ans+1]=z
end
end
end
end

p1={
 v={
  pos(Bw/2,0),
  pos(Bw/2-150,Bh),
  pos(Bw/2+150,Bh)
 },
 p={
  {1,2},
  {1,3}
 },
 draw=draw
}

p2={
 v={
  pos(100,100),
  pos(Bw-100,100),
  pos(100,250),
  pos(Bw-100,250),
  pos(100,100),
  pos(100,250),
  pos(Bw-100,100),
  pos(Bw-100,250),
 },
 p={
  {1,2},
  {3,4},
  {5,6},
  {7,8}
 },
 draw=draw
}

o=ppoffscreen.new()
o:create(1,1)

o:pos(Bw/2-150,Bh)

function start()
 o:drag(pptouch())
 p1.v[2].x=o:pos().x
 p1.v[3].x=o:pos().x+300
 local ans={}
 cross(p2,p1,ans)
 p1:draw(g.white)
 p2:draw(g.cyan)
 for i=1,#ans do
  local a
  a=ans[i]
  g:move(0,16)
  local r
  r=pprect(a.x-4,a.y-4,8,8)
  g:fill(r,g.red)
 end
end