-1

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
import_hill
  • 101
  • 3
  • 3
    Is this your complete code? Currently you just remove and readd the Item when the Position overlaps. Have you seen the examples on github: https://github.com/ruby2d/examples and the documentation in http://ruby2d.com ? – Christian Aug 19 '19 at 12:40
  • The code wouldn't even work because hit() doesn't return anything. Add a return statement to hit – pr0f3ss Aug 20 '19 at 09:29
  • 1
    @pr0f3ss `hit` return true/false as `&&` result. Return in ruby is implicit. – Nifriz Aug 20 '19 at 09:47

1 Answers1

3
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.