The logic and coding is almost the same with a bit of differences from Actionscript 3.0.
You can check out the BOUNCY - AS 3.0 Tutorial from my earlier post for comparison.
Silverlight Code :
Class : MainPage
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace Bouncy
{
public partial class MainPage : UserControl
{
double G;
double E;
double epsilon;
Ball ball;
double rightWallX;
double leftWallX;
public int score;
public MainPage()
{
// Required to initialize variables
InitializeComponent();
init();
CompositionTarget.Rendering += onEnterFrame;
}
void init(){
this.G = 0.27;
this.E = 0.65;
this.epsilon = 0.5;
ball = new Ball(this);
Canvas.SetLeft(ball, 275);
Canvas.SetTop(ball, 200);
LayoutRoot.Children.Add(ball);
score = 0;
this.scoreTxt.Text = score + "";
}
void onEnterFrame(object sender, EventArgs e){
//if(Math.Abs(ball.speedY)<0.01)
// collision - ground
if(Canvas.GetTop(ball)+ball.speedY > 300){
if(score != 0){
score = 0;
this.scoreTxt.Text = score + "";
}
if(Math.Abs(ball.speedY)>this.epsilon){
ball.speedY = -ball.speedY*E;
// add friction when on ground
ball.speedX *= 0.9;
}
else{
ball.speedY=0;
//Canvas.SetTop(ball, 300);
}
}
else if(Canvas.GetTop(ball) < 299){
ball.speedY += G;
}
// collision - right wall n left wall
if(Canvas.GetLeft(ball) > 510){
ball.speedX = -ball.speedX;
}
else if(Canvas.GetLeft(ball) < 40){
ball.speedX = -ball.speedX;
}
/*if(ball.speedY != 0){
ball.speedY += G;
}*/
if(ball.speedY == 0){
// add friction when on ground
ball.speedX *= 0.9;
}
Canvas.SetLeft(ball, Canvas.GetLeft(ball)+ball.speedX);
Canvas.SetTop(ball,Canvas.GetTop(ball)+ball.speedY);
}
public void increaseScore(){
score++;
scoreTxt.Text = score + "";
}
}
}
Class : Ball
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace Bouncy
{
public partial class Ball : UserControl
{
public double speedX;
public double speedY;
MainPage par;
public Ball(MainPage p)
{
// Required to initialize variables
InitializeComponent();
speedX = speedY = 0;
par = p;
}
public void move(){
// move
Canvas.SetLeft(this,Canvas.GetLeft(this)+this.speedX);
Canvas.SetTop(this,Canvas.GetTop(this)+this.speedY);
}
private void Ellipse_MouseLeftButtonDown(object sender,
System.Windows.Input.MouseButtonEventArgs e)
{
// TODO: Add event handler implementation here.
// increase score
par.increaseScore();
speedY = -6;
Random r = new Random();
speedX = r.NextDouble() * 14 - 7;
}
}
}
No comments:
Post a Comment
What do u feel ?