c# - Set properties of an object to be relative to another property of the same object -
i have method detects collision between ball , left paddle in classic game "pong". have made variables different parts of ball , paddle, in order make collision detection method easier understand. here method (and work).
public bool detectballpaddle1collision() { var ballbottom = _ball.y + ball.width; var balltop = _ball.y; var ballleft = _ball.x; var ballright = _ball.x + ball.width; var paddle1bottom = _paddle1.y + paddle.height; var paddle1top = _paddle1.y; var paddle1left = playerpaddle.x; var paddle1right = playerpaddle.x + paddle.width; if (balltop < paddle1bottom && ballbottom > paddle1top && ballleft < paddle1right) { return true; } else { return false; } }
i refactor this, have variables different parts of ball, in ball class, so:
namespace pong.core.models { public abstract class ball : iball { public int y { get; set; } public int x { get; set; } public int vx { get; set; } public int vy { get; set; } public static int width; public static int speed; public int bottom { get; set; } public int top { get; set; } public int left { get; set; } public int right { get; set; } public ball() { this.setdirection ("left"); bottom = y + ball.width; top = y; left = x; right = x + ball.width; }
which enables me change ball/paddle1 collision detection method this:
public bool detectballpaddle1collision() { var paddle1bottom = _paddle1.y + paddle.height; var paddle1top = _paddle1.y; var paddle1left = playerpaddle.x; var paddle1right = playerpaddle.x + paddle.width; if (_ball.top < paddle1bottom && _ball.bottom > paddle1top && _ball.left < paddle1right) { return true; } else { return false; } }
theoretically should work, doesn't, ball goes through paddle. should work because property method, , supposed keep updating if relative property, correct? why made ball.bottom, .top, .left , .right, properties getters , setters rather fields not keep updating.
when specify properties { get; set; } happens compiler creating private field , keeps property value in it.
setting top property value y in constructor put initial value of y private field , value never updated y changes.
instead, implement properties this:
(this work assuming x , y being updated during game)
public class ball : iball { public int y { get; set; } public int x { get; set; } public int vx { get; set; } public int vy { get; set; } public static int width; public static int speed; public int top { { return y; } } public int left { { return x; } } public int right { { return x + ball.width; } } public int bottom { { return y + ball.width; } } }
Comments
Post a Comment