使用对象在框中创建弹跳球,而不是工作

时间:2017-03-18 13:26:59

标签: javascript

我对javascript很新,我正在尝试做一个球在盒子/画布周围反弹的任务。我设法做了一次,但我现在正在使用对象重新创建它,我没有错误,但它没有工作,我真的不知道问题是什么。如果有人能指出我正确的方向,那将非常感谢你。帆布画出但没有球。

<canvas id="sCanvas" width="550" height="550" style="border: solid">   </canvas>
<body>

<script type="text/javascript">

    //variables
    var c = document.getElementById("sCanvas");
    var ctx = sCanvas.getContext("2d");
    var cHeight = sCanvas.height;
    var cWidth = sCanvas.width;


    //object


    //create the sphere object
    class Sphere {
        constructor(aRadius){
            //add properties to object
            this.radius = (aRadius || 15); //if paramater not set then make 15
            this.colour = "green"//"hsl"( + 360 * Math.random() + ",50%,50%");
                 //create propertes for xPos, yPos, speedX, speedY
            //and assign sensible values to them either
            //hard coded or random numbers
            //don't forget to use the format .this as above
            this.xPos = 30;
            this.yPos = 30;
            this.speedX = 2;
            this.speedY = 5;

        }

        drawMe(){
            //method to draw itself
            ctx.beginPath();
            ctx.arc(this.xPos, this.Ypos, this.radius, 0, Math.PI *2, true);
            ctx.fillStyle = this.colour;
            ctx.fill();
        }

        //method to move itself
        moveMe(){
            this.yPos += this.speedY;
            this.xPos += this.speedX;

            if (this.yPos > 540){
                //statement
                this.speedY =- this.speedY
            }

            else if (this.yPos < 10){
                //statement
                this.speedY =- this.speedY
            }

            if (this.xPos > 540){
                //statement
                this.speedX =- this.speedX
            }

            else if (this.xPos < 10){
                //statement
                this.speedX =- this.speedX
            }
        }
    }


//create a new instance if sphere - called ball
    var ball = new Sphere();
    //assign a 'new' instance of 'sphere()' here.

    //redraw the screen each time to create animation
        function render(){
            //recall render() using requestAnimationFrame API
            requestAnimationFrame(render);
            //clear canvas
            ctx.clearRect(0, 0, cWidth, cHeight);
            //call the drawME method of the ball object
            ball.drawMe();
            //call the moveMe method of the ball object
            ball.moveMe();


        }

     render(); //set the animation and drawing on canvas going


</script> 
</body>

1 个答案:

答案 0 :(得分:1)

在ctx.arc()的drawMe()函数中,你放了this.Ypos而不是this.yPos

您可能想要做的一个改变是在moveMe()方法中考虑球的大小,而不是对数字进行硬编码。我这样说是因为你在构造函数中将球半径设置为可变大小。

如果你将球的半径改为35,那么它的一部分将超过盒子撞到墙壁时的尺寸。

〜专利