Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

ruby - Collision Detection Ruby2d

I have posted a question similar to this and still have no clue on what steps forward I should take. I am trying to make the computer detect if the square touches the circle.

I have seen some code that could probably work but am not able to implement it into my script. Please provide an edited piece of my code below, thanks!

EDIT: I have tried putting a return command but it still does not work, I have posted my whole script below to provide as much info as I can. Thanks again!

require 'ruby2d'
set title: 'Merdeka', background: 'olive'
set width: 600, height: 500
s = Square.new(
  x: @x, y: @y,
  size: 25,
  color: 'navy',
  z: 10
)
a = Circle.new(
  x: rand(600), y: rand(500),
  radius: 11,
  sectors: 32,
  color: 'maroon',
  z: 10
)

@x_speed = 0
@y_speed = 0
on :key_down do |event|
  if event.key == 'up'
    @x_speed = 0
    @y_speed = -2
  elsif event.key == 'right'
    @x_speed = 2
    @y_speed = 0
  elsif event.key == 'down'
    @x_speed = 0
    @y_speed = 2
  elsif event.key == 'left'
    @x_speed = -2
    @y_speed = 0
  end
end

update do
  s.x += @x_speed
  s.y += @y_speed
end
def hit(a, s)
  return a.x == s.x && a.y == s.y
end
if hit(a, s)
a.remove
a.add
end
show
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
def hit(a, s)
  return a.contains?(s.x + a.radius ,s.y +a.radius)
end

this will get you close, triangles have sloped edges so if you want to be extremely accurate you will need to apply some math.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...