Search Results

Search found 52 results on 3 pages for 'vy clarks'.

Page 1/3 | 1 2 3  | Next Page >

  • Recreating Doodle Jump in Canvas - Platforms spawning out of reach

    - by kushsolitary
    I have started to recreate Doodle Jump in HTML using Canvas. Here's my current progress. As you can see, if you play it for a few seconds, some platforms will be out of the player's reach. I don't know why is this happening. Here's the code which is responsible for the re-spawning of platforms. //Movement of player affected by gravity if(player.y > (height / 2) - (player.height / 2)) { player.y += player.vy; player.vy += gravity; } else { for(var i = 0; i < platforms.length; i++) { var p = platforms[i]; if(player.vy < 0) { p.y -= player.vy; player.vy += 0.08; } if(p.y > height) { position = 0; var h = p.y; platforms[i] = new Platform(); } if(player.vy >= 0) { player.y += player.vy; player.vy += gravity; } } } Also, here's the platform class. //Platform class function Platform(y) { this.image = new Image(); this.image.src = platformImg; this.width = 105; this.height = 25; this.x = Math.random() * (width - this.width); this.y = y || position; position += height / platformCount; //Function to draw it this.draw = function() { try { ctx.drawImage(this.image, this.x, this.y, this.width, this.height); } catch(e) {} }; } You can also see the whole code on the link I provided. Also, when a platform goes out of the view port, the jump animation becomes quirky. I am still trying to find out what's causing this but can't find any solution.

    Read the article

  • refactoring this function in Java

    - by Joel
    Hi folks, I'm learning Java, and I know one of the big complaints about newbie programmers is that we make really long and involved methods that should be broken into several. Well here is one I wrote and is a perfect example. :-D. public void buildBall(){ /* sets the x and y value for the center of the canvas */ double i = ((getWidth() / 2)); double j = ((getHeight() / 2)); /* randomizes the start speed of the ball */ vy = 3.0; vx = rgen.nextDouble(1.0, 3.0); if (rgen.nextBoolean(.05)) vx = -vx; /* creates the ball */ GOval ball = new GOval(i,j,(2 *BALL_RADIUS),(2 * BALL_RADIUS)); ball.setFilled(true); ball.setFillColor(Color.RED); add(ball); /* animates the ball */ while(true){ i = (i + (vx* 2)); j = (j + (vy* 2)); if (i > APPLICATION_WIDTH-(2 * BALL_RADIUS)){ vx = -vx; } if (j > APPLICATION_HEIGHT-(2 * BALL_RADIUS)){ vy = -vy; } if (i < 0){ vx = -vx; } if (j < 0){ vy = -vy; } ball.move(vx + vx, vy + vy); pause(10); /* checks the edges of the ball to see if it hits an object */ colider = getElementAt(i, j); if (colider == null){ colider = getElementAt(i + (2*BALL_RADIUS), j); } if (colider == null){ colider = getElementAt(i + (2*BALL_RADIUS), j + (2*BALL_RADIUS)); } if (colider == null){ colider = getElementAt(i, j + (2*BALL_RADIUS)); } /* If the ball hits an object it reverses direction */ if (colider != null){ vy = -vy; /* removes bricks when hit but not the paddle */ if (j < (getHeight() -(PADDLE_Y_OFFSET + PADDLE_HEIGHT))){ remove(colider); } } } You can see from the title of the method that I started with good intentions of "building the ball". There are a few issues I ran up against: The problem is that then I needed to move the ball, so I created that while loop. I don't see any other way to do that other than just keep it "true", so that means any other code I create below this loop won't happen. I didn't make the while loop a different function because I was using those variables i and j. So I don't see how I can refactor beyond this loop. So my main question is: How would I pass the values of i and j to a new method: "animateBall" and how would I use ball.move(vx + vx, vy + vy); in that new method if ball has been declared in the buildBall method? I understand this is probably a simple thing of better understanding variable scope and passing arguments, but I'm not quite there yet...

    Read the article

  • Drawing random smooth lines contained in a square [migrated]

    - by Doug Mercer
    I'm trying to write a matlab function that creates random, smooth trajectories in a square of finite side length. Here is my current attempt at such a procedure: function [] = drawroutes( SideLength, v, t) %DRAWROUTES Summary of this function goes here % Detailed explanation goes here %Some parameters intended to help help keep the particles in the box RandAccel=.01; ConservAccel=0; speedlimit=.1; G=10^(-8); % %Initialize Matrices Ax=zeros(v,10*t); Ay=Ax; vx=Ax; vy=Ax; x=Ax; y=Ax; sx=zeros(v,1); sy=zeros(v,1); % %Define initial position in square x(:,1)=SideLength*.15*ones(v,1)+(SideLength*.7)*rand(v,1); y(:,1)=SideLength*.15*ones(v,1)+(SideLength*.7)*rand(v,1); % for i=2:10*t %Measure minimum particle distance component wise from boundary %for each vehicle BorderGravX=[abs(SideLength*ones(v,1)-x(:,i-1)),abs(x(:,i-1))]'; BorderGravY=[abs(SideLength*ones(v,1)-y(:,i-1)),abs(y(:,i-1))]'; rx=min(BorderGravX)'; ry=min(BorderGravY)'; % %Set the sign of the repulsive force for k=1:v if x(k,i)<.5*SideLength sx(k)=1; else sx(k)=-1; end if y(k,i)<.5*SideLength sy(k)=1; else sy(k)=-1; end end % %Calculate Acceleration w/ random "nudge" and repulive force Ax(:,i)=ConservAccel*Ax(:,i-1)+RandAccel*(rand(v,1)-.5*ones(v,1))+sx*G./rx.^2; Ay(:,i)=ConservAccel*Ay(:,i-1)+RandAccel*(rand(v,1)-.5*ones(v,1))+sy*G./ry.^2; % %Ad hoc method of trying to slow down particles from jumping outside of %feasible region for h=1:v if abs(vx(h,i-1)+Ax(h,i))<speedlimit vx(h,i)=vx(h,i-1)+Ax(h,i); elseif (vx(h,i-1)+Ax(h,i))<-speedlimit vx(h,i)=-speedlimit; else vx(h,i)=speedlimit; end end for h=1:v if abs(vy(h,i-1)+Ay(h,i))<speedlimit vy(h,i)=vy(h,i-1)+Ay(h,i); elseif (vy(h,i-1)+Ay(h,i))<-speedlimit vy(h,i)=-speedlimit; else vy(h,i)=speedlimit; end end % %Update position x(:,i)=x(:,i-1)+(vx(:,i-1)+vx(:,i))/2; y(:,i)=y(:,i-1)+(vy(:,i-1)+vy(:,1))/2; % end %Plot position clf; hold on; axis([-100,SideLength+100,-100,SideLength+100]); cc=hsv(v); for j=1:v plot(x(j,1),y(j,1),'ko') plot(x(j,:),y(j,:),'color',cc(j,:)) end hold off; % end My original plan was to place particles within a square, and move them around by allowing their acceleration in the x and y direction to be governed by a uniformly distributed random variable. To keep the particles within the square, I tried to create a repulsive force that would push the particles away from the boundaries of the square. In practice, the particles tend to leave the desired "feasible" region after a relatively small number of time steps (say, 1000)." I'd love to hear your suggestions on either modifying my existing code or considering the problem from another perspective. When reading the code, please don't feel the need to get hung up on any of the ad hoc parameters at the very beginning of the script. They seem to help, but I don't believe any beside the "G" constant should truly be necessary to make this system work. Here is an example of the current output: Many of the vehicles have found their way outside of the desired square region, [0,400] X [0,400].

    Read the article

  • Multiple setInterval in a HTML5 Canvas game

    - by kushsolitary
    I'm trying to achieve multiple animations in a game that I am creating using Canvas (it is a simple ping-pong game). This is my first game and I am new to canvas but have created a few experiments before so I have a good knowledge about how canvas work. First, take a look at the game here. The problem is, when the ball hits the paddle, I want a burst of n particles at the point of contact but that doesn't came right. Even if I set the particles number to 1, they just keep coming from the point of contact and then hides automatically after some time. Also, I want to have the burst on every collision but it occurs on first collision only. I am pasting the code here: //Initialize canvas var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d"), W = window.innerWidth, H = window.innerHeight, particles = [], ball = {}, paddles = [2], mouse = {}, points = 0, fps = 60, particlesCount = 50, flag = 0, particlePos = {}; canvas.addEventListener("mousemove", trackPosition, true); //Set it's height and width to full screen canvas.width = W; canvas.height = H; //Function to paint canvas function paintCanvas() { ctx.globalCompositeOperation = "source-over"; ctx.fillStyle = "black"; ctx.fillRect(0, 0, W, H); } //Create two paddles function createPaddle(pos) { //Height and width this.h = 10; this.w = 100; this.x = W/2 - this.w/2; this.y = (pos == "top") ? 0 : H - this.h; } //Push two paddles into the paddles array paddles.push(new createPaddle("bottom")); paddles.push(new createPaddle("top")); //Setting up the parameters of ball ball = { x: 2, y: 2, r: 5, c: "white", vx: 4, vy: 8, draw: function() { ctx.beginPath(); ctx.fillStyle = this.c; ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false); ctx.fill(); } }; //Function for creating particles function createParticles(x, y) { this.x = x || 0; this.y = y || 0; this.radius = 0.8; this.vx = -1.5 + Math.random()*3; this.vy = -1.5 + Math.random()*3; } //Draw everything on canvas function draw() { paintCanvas(); for(var i = 0; i < paddles.length; i++) { p = paddles[i]; ctx.fillStyle = "white"; ctx.fillRect(p.x, p.y, p.w, p.h); } ball.draw(); update(); } //Mouse Position track function trackPosition(e) { mouse.x = e.pageX; mouse.y = e.pageY; } //function to increase speed after every 5 points function increaseSpd() { if(points % 4 == 0) { ball.vx += (ball.vx < 0) ? -1 : 1; ball.vy += (ball.vy < 0) ? -2 : 2; } } //function to update positions function update() { //Move the paddles on mouse move if(mouse.x && mouse.y) { for(var i = 1; i < paddles.length; i++) { p = paddles[i]; p.x = mouse.x - p.w/2; } } //Move the ball ball.x += ball.vx; ball.y += ball.vy; //Collision with paddles p1 = paddles[1]; p2 = paddles[2]; if(ball.y >= p1.y - p1.h) { if(ball.x >= p1.x && ball.x <= (p1.x - 2) + (p1.w + 2)){ ball.vy = -ball.vy; points++; increaseSpd(); particlePos.x = ball.x, particlePos.y = ball.y; flag = 1; } } else if(ball.y <= p2.y + 2*p2.h) { if(ball.x >= p2.x && ball.x <= (p2.x - 2) + (p2.w + 2)){ ball.vy = -ball.vy; points++; increaseSpd(); particlePos.x = ball.x, particlePos.y = ball.y; flag = 1; } } //Collide with walls if(ball.x >= W || ball.x <= 0) ball.vx = -ball.vx; if(ball.y > H || ball.y < 0) { clearInterval(int); } if(flag == 1) { setInterval(emitParticles(particlePos.x, particlePos.y), 1000/fps); } } function emitParticles(x, y) { for(var k = 0; k < particlesCount; k++) { particles.push(new createParticles(x, y)); } counter = particles.length; for(var j = 0; j < particles.length; j++) { par = particles[j]; ctx.beginPath(); ctx.fillStyle = "white"; ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false); ctx.fill(); par.x += par.vx; par.y += par.vy; par.radius -= 0.02; if(par.radius < 0) { counter--; if(counter < 0) particles = []; } } } var int = setInterval(draw, 1000/fps); Now, my function for emitting particles is on line 156, and I have called this function on line 151. The problem here can be because of I am not resetting the flag variable but I tried doing that and got more weird results. You can check that out here. By resetting the flag variable, the problem of infinite particles gets resolved but now they only animate and appear when the ball collides with the paddles. So, I am now out of any solution.

    Read the article

  • HTML5 platformer collision detection problem

    - by fnx
    I'm working on a 2D platformer game, and I'm having a lot of trouble with collision detection. I've looked trough some tutorials, questions asked here and Stackoverflow, but I guess I'm just too dumb to understand what's wrong with my code. I've wanted to make simple bounding box style collisions and ability to determine on which side of the box the collision happens, but no matter what I do, I always get some weird glitches, like the player gets stuck on the wall or the jumping is jittery. You can test the game here: Platform engine test. Arrow keys move and z = run, x = jump, c = shoot. Try to jump into the first pit and slide on the wall. Here's the collision detection code: function checkCollisions(a, b) { if ((a.x > b.x + b.width) || (a.x + a.width < b.x) || (a.y > b.y + b.height) || (a.y + a.height < b.y)) { return false; } else { handleCollisions(a, b); return true; } } function handleCollisions(a, b) { var a_top = a.y, a_bottom = a.y + a.height, a_left = a.x, a_right = a.x + a.width, b_top = b.y, b_bottom = b.y + b.height, b_left = b.x, b_right = b.x + b.width; if (a_bottom + a.vy > b_top && distanceBetween(a_bottom, b_top) + a.vy < distanceBetween(a_bottom, b_bottom)) { a.topCollision = true; a.y = b.y - a.height + 2; a.vy = 0; a.canJump = true; } else if (a_top + a.vy < b_bottom && distanceBetween(a_top, b_bottom) + a.vy < distanceBetween(a_top, b_top)) { a.bottomCollision = true; a.y = b.y + b.height; a.vy = 0; } else if (a_right + a.vx > b_left && distanceBetween(a_right, b_left) < distanceBetween(a_right, b_right)) { a.rightCollision = true; a.x = b.x - a.width - 3; //a.vx = 0; } else if (a_left + a.vx < b_right && distanceBetween(a_left, b_right) < distanceBetween(a_left, b_left)) { a.leftCollision = true; a.x = b.x + b.width + 3; //a.vx = 0; } } function distanceBetween(a, b) { return Math.abs(b-a); }

    Read the article

  • Why a graphics overflow problem as a result of a for loop?

    - by sonny5
    using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Drawing.Imaging; using System.Drawing.Drawing2D; public class Form1 : System.Windows.Forms.Form { public static float WXmin; public static float WYmin; public static float WXmax; public static float WYmax; public static int VXmin; public static int VYmin; public static int VXmax; public static int VYmax; public static float Wx; public static float Wy; public static float Vx; public static float Vy; public Form1() { InitializeComponent(); } private void InitializeComponent() { this.ClientSize = new System.Drawing.Size(400, 300); this.Text="Pass Args"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.doLine); //this.Paint += new System.PaintEventHandler(this.eachCornerPix); //eachCornerPix(out Wx, out Wy, out Vx, out Vy); } static void Main() { Application.Run(new Form1()); } private void doLine(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.White, this.ClientRectangle); Pen p = new Pen(Color.Black); g.DrawLine(p, 0, 0, 100, 100); // draw DOWN in y, which is positive since no matrix called eachCornerPix(sender, e, out Wx, out Wy, out Vx, out Vy); p.Dispose(); } private void eachCornerPix (object sender, System.EventArgs e, out float Wx, out float Wy, out float Vx, out float Vy) { Wx = 0.0f; Wy = 0.0f; Vx = 0.0f; Vy = 0.0f; Graphics g = this.CreateGraphics(); Pen penBlu = new Pen(Color.Blue, 2); SolidBrush redBrush = new SolidBrush(Color.Red); int width = 2; // 1 pixel wide in x int height = 2; float [] Wxc = {0.100f, 5.900f, 5.900f, 0.100f}; float [] Wyc = {0.100f, 0.100f, 3.900f, 3.900f}; Console.WriteLine("Wxc[0] = {0}", Wxc[0]); Console.WriteLine("Wyc[3] = {0}", Wyc[3]); /* for (int i = 0; i<3; i++) { Wx = Wxc[i]; Wy = Wyc[i]; Vx = ((Wx - WXmin)*((VXmax-VXmin)+VXmin)/(WXmax-WXmin)); Vy = ((Wy - WYmin)*(VYmax-VYmin)/(WYmax-WYmin)+VYmin); Console.WriteLine("eachCornerPix Vx= {0}", Vx); Console.WriteLine("eachCornerPix Vy= {0}", Vy); g.FillRectangle(redBrush, Vx, Vy, width, height); } */ // What is there about this for loop that will not run? // When the comments above and after the for loop are removed, it gets an overflow? g.Dispose(); } }

    Read the article

  • 2D Collision in Canvas - Balls Overlapping When Velocity is High

    - by kushsolitary
    I am doing a simple experiment in canvas using Javascript in which some balls will be thrown on the screen with some initial velocity and then they will bounce on colliding with each other or with the walls. I managed to do the collision with walls perfectly but now the problem is with the collision with other balls. I am using the following code for it: //Check collision between two bodies function collides(b1, b2) { //Find the distance between their mid-points var dx = b1.x - b2.x, dy = b1.y - b2.y, dist = Math.round(Math.sqrt(dx*dx + dy*dy)); //Check if it is a collision if(dist <= (b1.r + b2.r)) { //Calculate the angles var angle = Math.atan2(dy, dx), sin = Math.sin(angle), cos = Math.cos(angle); //Calculate the old velocity components var v1x = b1.vx * cos, v2x = b2.vx * cos, v1y = b1.vy * sin, v2y = b2.vy * sin; //Calculate the new velocity components var vel1x = ((b1.m - b2.m) / (b1.m + b2.m)) * v1x + (2 * b2.m / (b1.m + b2.m)) * v2x, vel2x = (2 * b1.m / (b1.m + b2.m)) * v1x + ((b2.m - b1.m) / (b2.m + b1.m)) * v2x, vel1y = v1y, vel2y = v2y; //Set the new velocities b1.vx = vel1x; b2.vx = vel2x; b1.vy = vel1y; b2.vy = vel2y; } } You can see the experiment here. The problem is, some balls overlap each other and stick together while some of them rebound perfectly. I don't know what is causing this issue. Here's my balls object if that matters: function Ball() { //Random Positions this.x = 50 + Math.random() * W; this.y = 50 + Math.random() * H; //Random radii this.r = 15 + Math.random() * 30; this.m = this.r; //Random velocity components this.vx = 1 + Math.random() * 4; this.vy = 1 + Math.random() * 4; //Random shade of grey color this.c = Math.round(Math.random() * 200); this.draw = function() { ctx.beginPath(); ctx.fillStyle = "rgb(" + this.c + ", " + this.c + ", " + this.c + ")"; ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false); ctx.fill(); ctx.closePath(); } }

    Read the article

  • error CS0177: The out parameter 'Wx' must be assigned to before control leaves the current method

    - by sonny5
    using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; public class Form1 : System.Windows.Forms.Form { public static float WXmin; public static float WYmin; public static float WXmax; public static float WYmax; public static int VXmin; public static int VYmin; public static int VXmax; public static int VYmax; public static float Vx; public static float Vy; public Form1() { InitializeComponent(); } private void InitializeComponent() { //this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(400, 300); this.Text="Pass Args"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.doLine); } static void Main() { Application.Run(new Form1()); } private void doLine(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.White, this.ClientRectangle); Pen p = new Pen(Color.Black); g.DrawLine(p, 0, 0, 100, 100); p.Dispose(); } private void eachCornerPix (object sender, PaintEventArgs e, out float Wx, out float Wy, out float Vx, out float Vy) { Graphics g = this.CreateGraphics(); Pen penBlu = new Pen(Color.Blue, 2); SolidBrush redBrush = new SolidBrush(Color.Red); int width = 2; // 1 pixel wide in x int height = 2; float [] Wxc = {0.100f, 5.900f, 5.900f, 0.100f}; float [] Wyc = {0.100f, 0.100f, 3.900f, 3.900f}; for (int i = 0; i<3; i++) { Wx = Wxc[i]; Wy = Wyc[i]; Vx = ((Wx - WXmin)*((VXmax-VXmin)+VXmin)/(WXmax-WXmin)); Vy = ((Wy - WYmin)*(VYmax-VYmin)/(WYmax-WYmin)+VYmin); Console.WriteLine("eachCornerPix Vx= {0}", Vx); Console.WriteLine("eachCornerPix Vy= {0}", Vy); g.FillRectangle(redBrush, Vx, Vy, width, height); g.Dispose(); } // Desired effect: Use the array values (Wxc, Wyc) and re-assign them to Wx and Wy. Then use // Wx and Wy as components to calculate Vx and Vy. // My end goal...once compile issues are resolved, is to pass each array value listed // using this method. This should allow 4 xy point pairs to be plotted. // Errors: // pass1.cs(51,18): error CS0177: The out parameter 'Wx' must be assigned to before // control leaves the current method // pass1.cs(51,18): error CS0177: The out parameter 'Wy' must be assigned to before // control leaves the current method // pass1.cs(51,18): error CS0177: The out parameter 'Vx' must be assigned to before // control leaves the current method // pass1.cs(51,18): error CS0177: The out parameter 'Vy' must be assigned to before // control leaves the current method } }

    Read the article

  • collsion issues with quadtree [on hold]

    - by QuantumGamer
    So i implemented a Quad tree in Java for my 2D game and everything works fine except for when i run my collision detection algorithm, which checks if a object has hit another object and which side it hit.My problem is 80% of the time the collision algorithm works but sometimes the objects just go through each other. Here is my method: private void checkBulletCollision(ArrayList object) { quad.clear(); // quad is the quadtree object for(int i=0; i < object.size();i++){ if(object.get(i).getId() == ObjectId.Bullet) // inserts the object into quadtree quad.insert((Bullet)object.get(i)); } ArrayList<GameObject> returnObjects = new ArrayList<>(); // Uses Quadtree to determine to calculate how many // other bullets it can collide with for(int i=0; i < object.size(); i++){ returnObjects.clear(); if(object.get(i).getId() == ObjectId.Bullet){ quad.retrieve(returnObjects, object.get(i).getBoundsAll()); for(int k=0; k < returnObjects.size(); k++){ Bullet bullet = (Bullet) returnObjects.get(k); if(getBoundsTop().intersects(bullet.getBoundsBottom())){ vy = speed; bullet.vy = -speed; } if(getBoundsBottom().intersects(bullet.getBoundsTop())){ vy = -speed; bullet.vy = speed; } if(getBoundsLeft().intersects(bullet.getBoundsRight())){ vx =speed; bullet.vx = -speed; } if(getBoundsRight().intersects(bullet.getBoundsLeft())){ vx = -speed; bullet.vx = speed; } } } } } Any help would be appreciated. Thanks in advance.

    Read the article

  • How can I Implement KeyListeners/ActionListeners into the JFrame?

    - by A.K.
    I'll get to the point: I have a player in my game that you control with the keyboard yet the key methods in the player class and ActionListener w/ KeyAdapter in the Board class don't seem to fire. So far I've tried adding these key methods into the JFrame, doesn't seem to let me move him even though other objects that I have (enemies) can move fine. Here's part of the JFrame class with the event listeners: frm.addKeyListener(KeyBoardListener); public void mouseClicked(MouseEvent e) { nSound.play(); StartB.setContentAreaFilled(false); cards.remove(StartB); frm.remove(TitleL); frm.remove(cards); frm.setLayout(new GridLayout(1, 1)); frm.add(nBoard); //Add Game "Tiles" Or Content. x = 1200 nBoard.setPreferredSize(new Dimension(1200, 420)); cards.revalidate(); frm.validate(); } public KeyListener KeyBoardListener = new KeyListener() { @Override public void keyPressed(KeyEvent args0) { int key = args0.getKeyCode(); if(key == KeyEvent.VK_LEFT) { nBoard.S.vx = -4; } if(key == KeyEvent.VK_RIGHT) { nBoard.S.vx = 4; } if(key == KeyEvent.VK_UP) { nBoard.S.vy = -4; } if(key == KeyEvent.VK_DOWN) { nBoard.S.vy = 4; } if(key == KeyEvent.VK_SPACE) { nBoard.S.fire(); } } @Override public void keyReleased(KeyEvent args0) { int key = args0.getKeyCode(); if(key == KeyEvent.VK_LEFT) { nBoard.S.vx = 0; } if(key == KeyEvent.VK_RIGHT) { nBoard.S.vx = 0; } if(key == KeyEvent.VK_UP) { nBoard.S.vy = 0; } if(key == KeyEvent.VK_DOWN) { nBoard.S.vy = 0; } } @Override public void keyTyped(KeyEvent args0) { // TODO Auto-generated method stub } };

    Read the article

  • Android draw using SurfaceView and Thread

    - by Morten Høgseth
    I am trying to draw a ball to my screen using 3 classes. I have read a little about this and I found a code snippet that works using the 3 classes on one page, Playing with graphics in Android I altered the code so that I have a ball that is moving and shifts direction when hitting the wall like the picture below (this is using the code in the link). Now I like to separate the classes into 3 different pages for not making everything so crowded, everything is set up the same way. Here are the 3 classes I have. BallActivity.java Ball.java BallThread.java package com.brick.breaker; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class BallActivity extends Activity { private Ball ball; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); ball = new Ball(this); setContentView(ball); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); setContentView(null); ball = null; finish(); } } package com.brick.breaker; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.SurfaceHolder; import android.view.SurfaceView; public class Ball extends SurfaceView implements SurfaceHolder.Callback { private BallThread ballThread = null; private Bitmap bitmap; private float x, y; private float vx, vy; public Ball(Context context) { super(context); // TODO Auto-generated constructor stub bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ball); x = 50.0f; y = 50.0f; vx = 10.0f; vy = 10.0f; getHolder().addCallback(this); ballThread = new BallThread(getHolder(), this); } protected void onDraw(Canvas canvas) { update(canvas); canvas.drawBitmap(bitmap, x, y, null); } public void update(Canvas canvas) { checkCollisions(canvas); x += vx; y += vy; } public void checkCollisions(Canvas canvas) { if(x - vx < 0) { vx = Math.abs(vx); } else if(x + vx > canvas.getWidth() - getBitmapWidth()) { vx = -Math.abs(vx); } if(y - vy < 0) { vy = Math.abs(vy); } else if(y + vy > canvas.getHeight() - getBitmapHeight()) { vy = -Math.abs(vy); } } public int getBitmapWidth() { if(bitmap != null) { return bitmap.getWidth(); } else { return 0; } } public int getBitmapHeight() { if(bitmap != null) { return bitmap.getHeight(); } else { return 0; } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub ballThread.setRunnable(true); ballThread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub boolean retry = true; ballThread.setRunnable(false); while(retry) { try { ballThread.join(); retry = false; } catch(InterruptedException ie) { //Try again and again and again } break; } ballThread = null; } } package com.brick.breaker; import android.graphics.Canvas; import android.view.SurfaceHolder; public class BallThread extends Thread { private SurfaceHolder sh; private Ball ball; private Canvas canvas; private boolean run = false; public BallThread(SurfaceHolder _holder,Ball _ball) { sh = _holder; ball = _ball; } public void setRunnable(boolean _run) { run = _run; } public void run() { while(run) { canvas = null; try { canvas = sh.lockCanvas(null); synchronized(sh) { ball.onDraw(canvas); } } finally { if(canvas != null) { sh.unlockCanvasAndPost(canvas); } } } } public Canvas getCanvas() { if(canvas != null) { return canvas; } else { return null; } } } Here is a picture that shows the outcome of these classes. I've tried to figure this out but since I am pretty new to Android development I thought I could ask for help. Does any one know what is causing the ball to be draw like that? The code is pretty much the same as the one in the link and I have tried to experiment to find a solution but no luck. Thx in advance for any help=)

    Read the article

  • moving a sprite causes jerky movement

    - by mac_55
    I've got some jerky movement of my sprite. Basically, when the user touches a point on the screen, the sprite should move to that point. This is working mostly fine... it's even taking into account a delta - because frame rate may not be consistant. However, I notice that the y movement usually finishes before the x movement (even when the distances to travel are the same), so it appears like the sprite is moving in an 'L' shape rather than a smooth diagonal line. Vertical and horizontal velocity (vx, vy) are both set to 300. Any ideas what's wrong? How can I go about getting my sprite to move in a smooth diagonal line? - (void)update:(ccTime)dt { int x = self.position.x; int y = self.position.y; //if ball is to the left of target point if (x<targetx) { //if movement of the ball won't take it to it's target position if (x+(vx *dt) < targetx) { x += vx * dt; } else { x = targetx; } } else if (x>targetx) //same with x being too far to the right { if (x-(vx *dt) > targetx) { x -= vx * dt; } else { x = targetx; } } if (y<targety) { if (y+(vy*dt)<targety) { y += vy * dt; } else { y = targety; } } else if (y>targety) { if (y-(vy*dt)>targety) { y -= vy * dt; } else { y = targety; } } self.position = ccp(x,y); }

    Read the article

  • Collision disturbing the jumping mechanic in java 2D game [on hold]

    - by user50931
    So I have been working on a 2D Java game recently and everything was going smoothly, until I reached a problem to do with the players jumping mechanic. So far I've got the player to jump a fixed rate and fall due to gravity. Hers my code for my Player class. public class Player extends GameObject { public Player(int x, int y, int width, int height, ObjectId id) { super(x, y, width, height, id); } @Override public void tick(ArrayList<GameObject> object) { if(go){ x+=vx; y+=vy; } if(vx <0){ facing =-1; }else if(vx >0) facing =1; checkCollision(object); checkStance(); } private void checkStance() { if(falling){ //gravity jumping = false; vy = speed/2; } if(jumping){ // Calculates how high jump should be vy = -speed*2; if(jumpY - y >= maxJumpHeight) falling =true; } } private void checkCollision(ArrayList<GameObject> object) { for(int i=0; i< object.size(); i++ ){ GameObject tempObject = object.get(i); if(tempObject.getId() == ObjectId.Ledge){ if(getBoundsTop().intersects(tempObject.getBoundsAll())){ //Top y = tempObject.getY() + tempObject.getBoundsAll().height; falling =true; } if(getBoundsRight().intersects(tempObject.getBoundsAll())){ // Right x = tempObject.getX() -width ; } if(getBoundsLeft().intersects(tempObject.getBoundsAll())){ //Left x = tempObject.getX() + tempObject.getWidth(); } if(getBoundsBottom().intersects(tempObject.getBoundsAll())){ //Bottom y = tempObject.getY() - height; falling =false; vy=0; }else{ falling =true; } } } } @Override public void render(Graphics g) { g.setColor(Color.BLACK); g.fillRect((int)x, (int)y, width, height); } @Override public Rectangle getBoundsAll() { return new Rectangle((int)x, (int)y,width,height); } public Rectangle getBoundsTop() { return new Rectangle((int) x , (int)y ,width,height/15); } public Rectangle getBoundsBottom() { return new Rectangle( (int)x , (int) y +height -(height /15),width,height/15); } public Rectangle getBoundsLeft() { return new Rectangle( (int) x , (int) y + height /10 ,width/8,height - (height /5)); } public Rectangle getBoundsRight() { return new Rectangle((int) x + width - (width/8) ,(int) y + height /10 ,width/8,height - height/5); } } My problem is when I add: else{ falling =true; } during the loop of the ArrayList to check collision, it stops the player from jumping and keeps him on the ground. I've tried to find a way around this but haven't had any luck. Any suggestions?

    Read the article

  • Determining the angle to fire a shot when target and shooter moves, and bullet moves with shooter velocity added in

    - by Azaral
    I saw this question: Predicting enemy position in order to have an object lead its target and followed the link in the answer to stack overflow. In the stack overflow page I used the 2nd answer, the one that is a large mathematical derivation. My situation is a little different though. My first question though is will the answer provided in the stack overflow page even work to begin with, assuming the original circumstances of moving target and stationary shooter. My situation is a little different than that situation. My target moves, the shooter moves, and the bullets from the shooter start off with the velocities in x and y added to the bullets' x and y velocities. If you are sliding to the right, the bullets will remain in front of you as you move so as long as your velocity remains constant. What I'm trying to do is to get the enemy to be able to determine where they need to shoot in order to hit the player. Unless the player and enemy is stationary, the velocity from the ship adding to the velocity of the bullets will cause a miss. I'd rather like to prevent that. I used the formula in the stack overflow answer and did what I thought were the appropriate adjustments. I've been banging at this for the last four hours and I just can't make it click. It is probably something really simple and boneheaded that I am missing (that seems to be a lot of my problems lately). Here is the solution presented from the stack overflow answer: It boils down to solving a quadratic equation of the form: a * sqr(x) + b * x + c == 0 Note that by sqr I mean square, as opposed to square root. Use the following values: a := sqr(target.velocityX) + sqr(target.velocityY) - sqr(projectile_speed) b := 2 * (target.velocityX * (target.startX - cannon.X) + target.velocityY * (target.startY - cannon.Y)) c := sqr(target.startX - cannon.X) + sqr(target.startY - cannon.Y) Now we can look at the discriminant to determine if we have a possible solution. disc := sqr(b) - 4 * a * c If the discriminant is less than 0, forget about hitting your target -- your projectile can never get there in time. Otherwise, look at two candidate solutions: t1 := (-b + sqrt(disc)) / (2 * a) t2 := (-b - sqrt(disc)) / (2 * a) Note that if disc == 0 then t1 and t2 are equal. If there are no other considerations such as intervening obstacles, simply choose the smaller positive value. (Negative t values would require firing backward in time to use!) Substitute the chosen t value back into the target's position equations to get the coordinates of the leading point you should be aiming at: aim.X := t * target.velocityX + target.startX aim.Y := t * target.velocityY + target.startY Here is my code, after being corrected by Sam Hocevar (thank you again for your help!). It still doesn't work. For some reason it never enters the section of code inside the if(disc = 0) (obviously because it is always less than zero but...). However, if I plug the numbers from my game log on the enemy and player positions and velocities it outputs a valid firing solution. I have looked at the code side by side a couple of times now and I can't find any differences. There has got to be something simple I'm missing here. If someone else could look at this code and determine what is going on here I'd appreciate it. I know it's not going through that section because if it were, shouldShoot would become true and the enemy would be blasting away at the player. This section calls the function in question, CalculateShootHeading() if(shouldMove) { UseEngines(); } x += xVelocity; y += yVelocity; CalculateShootHeading(); if(shouldShoot) { ShootWeapons(); } UpdateWeapons(); This is CalculateShootHeading(). This is inside the enemy class so x and y are the enemy's x and y and the same with velocity. One output from my game log gives Player X = 2108, Player Y = -180.956, Player X velocity = 10.9949, Player Y Velocity = -6.26017, Enemy X = 1988.31, Enemy Y = -339.051, Enemy X velocity = 1.81666, Enemy Y velocity = -9.67762, 0 enemy projectiles. The output from the console tester is Bullet position = 2210.49, -239.313 and Player Position = 2210.49, -239.313. This doesn't make any sense. The only thing that could be different is the code or the input into my function in the game and I've checked that and I don't think that it is wrong as it's updated before this and never changed. float const bulletSpeed = 30.f; float const dx = playerX - x; float const dy = playerY - y; float const vx = playerXVelocity - xVelocity; float const vy = playerYVelocity - yVelocity; float const a = vx * vx + vy * vy - bulletSpeed * bulletSpeed; float const b = 2.f * (vx * dx + vy * dy); float const c = dx * dx + dy * dy; float const disc = b * b - 4.f * a * c; shouldShoot = false; if (disc >= 0.f) { float t0 = (-b - std::sqrt(disc)) / (2.f * a); float t1 = (-b + std::sqrt(disc)) / (2.f * a); if (t0 < 0.f || (t1 < t0 && t1 >= 0.f)) { t0 = t1; } if (t0 >= 0.f) { float shootx = vx + dx / t0; float shooty = vy + dy / t0; heading = std::atan2(shooty, shootx) * RAD2DEGREE; } shouldShoot = true; }

    Read the article

  • Java: How to Make a Player Class in a Tile-Based RPG

    - by A.K.
    So I've been following a JavaHub tutorial that basically uses a pixel engine similar to MiniCraft. I've attempted to make a Player Class as such, and I'm basically making a mock Pokemon game for learning's sake: package pokemon.entity; import java.awt.Rectangle; import pokemon.gfx.Screen; import pokemon.levelgen.Tile; import pokemon.entity.SpritesManage;; public class Player { int x, y; int vx, vy; public Rectangle AshRec; public Sprite AshSprite; Screen screen; Sprite[][] AshSheet; public Player() { AshSprite = SpritesManage.AshSheet[1][0]; AshRec = new Rectangle(0, 0, 16, 16); x = 0; y = 0; vx = 1; vy = 1; screen.renderSprite(0, 0, AshSprite); } public void update() { move(); checkCollision(); } private void checkCollision() { } private void move() { AshRec.x += vx; AshRec.y += vy; } public void render(Screen screen, int x, int y) { screen.renderSprite(x, y, AshSprite); } } I guess what I really want to do is have the Player centered in the screen and have the sprite drawn based on an Input Handler. I'm just stumped as to how to sync these together.

    Read the article

  • 1136: Incorrect number of arguments. Expected 0.? AS3 Flash Cs4 (Round 2)

    - by charmaine
    (I have asked this before but I dont think I was direct enough with my question and therefore it did not get resolved so here goes again!) I am working through a book called Foundation Actionscript 3.0 Animation, making things move. I am now on Chapter 9 - Collision Detection. On two lines of my code I get the 1135 error, letting me know that I have an incorrect number of arguments. I have highlighted the two areas in which this occurs with asterisks: package { import flash.display.Sprite; import flash.events.Event; public class Bubbles extends Sprite { private var balls:Array; private var numBalls:Number = 10; private var centerBall:Ball; private var bounce:Number = -1; private var spring:Number = 0.2; public function Bubbles() { init(); } private function init():void { balls = new Array(); ***centerBall = new Ball(100, 0xcccccc);*** addChild(centerBall); centerBall.x = stage.stageWidth / 2; centerBall.y = stage.stageHeight / 2; for(var i:uint = 0; i < numBalls; i++) { ***var ball:Ball = new Ball(Math.random() * 40 + 5, Math.random() * 0xffffff);*** ball.x = Math.random() * stage.stageWidth; ball.y = Math.random() * stage.stageHeight; ball.vx = Math.random() * 6 - 3; ball.vy = Math.random() * 6 - 3; addChild(ball); balls.push(ball); } addEventListener(Event.ENTER_FRAME, onEnterFrame); } private function onEnterFrame(event:Event):void { for(var i:uint = 0; i < numBalls; i++) { var ball:Ball = balls[i]; move(ball); var dx:Number = ball.x - centerBall.x; var dy:Number = ball.y - centerBall.y; var dist:Number = Math.sqrt(dx * dx + dy * dy); var minDist:Number = ball.radius + centerBall.radius; if(dist < minDist) { var angle:Number = Math.atan2(dy, dx); var tx:Number = centerBall.x + Math.cos(angle) * minDist; var ty:Number = centerBall.y + Math.sin(angle) * minDist; ball.vx += (tx - ball.x) * spring; ball.vy += (ty - ball.y) * spring; } } } private function move(ball:Ball):void { ball.x += ball.vx; ball.y += ball.vy; if(ball.x + ball.radius > stage.stageWidth) { ball.x = stage.stageWidth - ball.radius; ball.vx *= bounce; } else if(ball.x - ball.radius < 0) { ball.x = ball.radius; ball.vx *= bounce; } if(ball.y + ball.radius > stage.stageHeight) { ball.y = stage.stageHeight - ball.radius; ball.vy *= bounce; } else if(ball.y - ball.radius < 0) { ball.y = ball.radius; ball.vy *= bounce; } } } } I think this is due to the non-existance of a Ball.as, when reading the tutorial I assumed it meant that I had to create a movie clip of a ball on stage and then export it for actionscript with the class name being Ball, however when flicking back through the book I saw that a Ball.as already existed, stating that I may need to use this again later on in the book, this read: package { import flash.display.Sprite; public class Ball extends Sprite { private var radius:Number; private var color:uint; public var vx:Number=0; public var vy:Number=0; public function Ball(radius:Number=40, color:uint=0xff0000) { this.radius=radius; this.color=color; init(); } public function init():void { graphics.beginFill(color); graphics.drawCircle(0, 0, radius); graphics.endFill(); } } } This managed to stop all the errors appearing however, it did not transmit any of the effects from Bubbles.as it just braught a Red Ball on the center of the stage. How would I alter this code in order to work in favour of Bubbles.as? Please Help! Thanks!

    Read the article

  • 1136: Incorrect number of arguments. Expected 0.? AS3 Flash Cs4

    - by charmaine
    Basically i am working through a book called..Foundation Actionscript 3.0 Animation, making things move. i am now on Chapter 9 - collision detection. On two lines of my code i get the 1135 error, letting me know that i have an incorrect number of arguments. Can anybody help me out on why this may be? package { import flash.display.Sprite; import flash.events.Event; public class Bubbles extends Sprite { private var balls:Array; private var numBalls:Number = 10; private var centerBall:Ball; private var bounce:Number = -1; private var spring:Number = 0.2; public function Bubbles() { init(); } private function init():void { balls = new Array(); centerBall = new Ball(100, 0xcccccc); addChild(centerBall); centerBall.x = stage.stageWidth / 2; centerBall.y = stage.stageHeight / 2; for(var i:uint = 0; i < numBalls; i++) { var ball:Ball = new Ball(Math.random() * 40 + 5, Math.random() * 0xffffff); ball.x = Math.random() * stage.stageWidth; ball.y = Math.random() * stage.stageHeight; ball.vx = Math.random() * 6 - 3; ball.vy = Math.random() * 6 - 3; addChild(ball); balls.push(ball); } addEventListener(Event.ENTER_FRAME, onEnterFrame); } private function onEnterFrame(event:Event):void { for(var i:uint = 0; i < numBalls; i++) { var ball:Ball = balls[i]; move(ball); var dx:Number = ball.x - centerBall.x; var dy:Number = ball.y - centerBall.y; var dist:Number = Math.sqrt(dx * dx + dy * dy); var minDist:Number = ball.radius + centerBall.radius; if(dist < minDist) { var angle:Number = Math.atan2(dy, dx); var tx:Number = centerBall.x + Math.cos(angle) * minDist; var ty:Number = centerBall.y + Math.sin(angle) * minDist; ball.vx += (tx - ball.x) * spring; ball.vy += (ty - ball.y) * spring; } } } ***private function move(ball:Ball):void*** { ball.x += ball.vx; ball.y += ball.vy; if(ball.x + ball.radius > stage.stageWidth) { ball.x = stage.stageWidth - ball.radius; ball.vx *= bounce; } else if(ball.x - ball.radius < 0) { ball.x = ball.radius; ball.vx *= bounce; } ***if(ball.y + ball.radius > stage.stageHeight)*** { ball.y = stage.stageHeight - ball.radius; ball.vy *= bounce; } else if(ball.y - ball.radius < 0) { ball.y = ball.radius; ball.vy *= bounce; } } } } The bold parts are the lines im having trouble with! please help..thanks in advance!!

    Read the article

  • From where does the game engines add location of an object?

    - by Player
    I have started making my first game( a pong game )with ruby (Gosu). I'm trying to detect the collision of two images using their location by comparing the location of the object (a ball) to another one(a player). For example: if (@player.x - @ball.x).abs <=184 && (@player.y - @ball.y).abs <= 40 @ball.vx = [email protected] @ball.vy = -@ball.vy But my problem is that with these numbers, the ball collides near the player sometimes, even though the dimensions of the player are correct. So my question is from where does the x values start to count? Is it from the center of gravity of the image or from the beginning of the image? (i.e When you add the image on a specific x,y,z what are these values compared to the image?

    Read the article

  • Outlook Web Access, reverse proxy and browser

    - by M'vy
    Hi SF'ers! We recently moved an exchange server behind a reverse proxy due to the loss of a public IP. I've managed to configure the reverse proxy (httpd proxy_http). But there is a problem for the SSL configuration. When accessing the OWA interface with Firefox, all is ok and working. When accessing with MSIE or Chrome, they do not retrieve the good SSL Certificate. I think this is due to the multiples virtual host for httpd. Is there a workaround to make sure MSIE/Chrome request the certificate for the good domain name like FF does? Already tested with the SSL virtual host : SetEnvIf User-Agent ".*MSIE.*" value BrowserMSIE Header unset WWW-Authenticate Header add WWW-Authenticate "Basic realm=exchange.domain.com" A: ProxyPreserveHost On also: BrowserMatch ".*MSIE.*" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 Or: SetEnvIf User-Agent ".*MSIE.*" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 And lots of ProxyPassand ProxyReversePath on /exchweb /exchange /public etc... And it still don't seem to work. Any clue? Thanks. Edit 1: Precision of versions # openssl version OpenSSL 0.9.8k-fips 25 Mar 2009 /usr/sbin/httpd -v Server version: Apache/2.2.11 (Unix) Server built: Mar 17 2009 09:15:10 Browser versions : MSIE : 8.0.6001 Opera: Version 11.01 Revision 1190 Firefox: 3.6.15 Chrome: 10.0.648.151 Operating System: Windows Vista 32bits. They are all SNI compliant, I've tested them this afternoon https://sni.velox.ch/ You're right Shane Madden, I have multiple sites on the same public IP (and same port as well). The server itself is just a reverse proxy, that rewrite addresses to internal servers. The default host is a dev site, configure with the certificate that does not match the OWA (of course... would have been to easy) <VirtualHost *:443> ServerName dev2.domain.com ServerAdmin [email protected] CustomLog "| /usr/sbin/rotatelogs /var/log/httpd/access-%y%m%d.log 86400" combined ErrorLog "| /usr/sbin/rotatelogs /var/log/httpd/error-%y%m%d.log 86400" LogLevel warn RewriteEngine on SetEnvIfNoCase X-Forwarded-For .+ proxy=yes SSLEngine on SSLProtocol -all +SSLv3 +TLSv1 SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL:+SSLv3 SSLCertificateFile /etc/httpd/ssl/domain.com.crt SSLCertificateKeyFile /etc/httpd/ssl/domain.com.key RewriteCond %{HTTP_HOST} dev2\.domain\.com RewriteRule ^/(.*)$ http://dev2.domain.com/$1 [L,P] </VirtualHost> The certificate of domain is a *.domain.com The second vHost is : <VirtualHost *:443> ServerName exchange.domain2.com ServerAdmin [email protected] CustomLog "| /usr/sbin/rotatelogs /var/log/httpd/exchange/access-%y%m%d.log 86400" combined ErrorLog "| /usr/sbin/rotatelogs /var/log/httpd/exchange/error-%y%m%d.log 86400" LogLevel warn SSLEngine on SSLProxyEngine On SSLProtocol -all +SSLv3 +TLSv1 SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL:+SSLv3 SSLCertificateFile /etc/httpd/ssl/exchange.pem SSLCertificateKeyFile /etc/httpd/ssl/exchange.key RewriteEngine on SetEnvIfNoCase X-Forwarded-For .+ proxy=yes RewriteCond %{HTTP_HOST} exchange\.domain2\.com RewriteRule ^/(.*)$ https://exchange.domain2.com/$1 [L,P] </VirtualHost> and it's certificate is exchange.domain2.com only. I presume the SNI is somewhere not activated on my server. The versions of openssl and apache seams to be ok for the SNI support. The only thing I do not know is if httpd has been compile with the good options. (I assume it's a fedora packet).

    Read the article

  • Delete on windows vista and seven -- discovery process

    - by M'vy
    Hi SUs! I've recently encountered a problem. Using svn at work I needed to clear some space. As you may know svn directories are full of sub-directories and files. So the delete process begins with a step of discovering the items to be deleted (I guess this is for displaying the progress bar). But in my case it ended up to be still running after I watched Braveheart (Off-topic: good film in my opinion. On-topic: and it last 2h50) and counting 440 000+ files. I finally decided to cut off the process and use the good old cmd with a del <directory> to do the job. (Done in some minutes) So I'm wondering if someone know how to override the system to make it actually begins the process while scanning the other items? At the end, I just want the file to be deleted and I don't care the number of files to be deleted. On the contrary I care about the time it takes. Thanks

    Read the article

  • Alert show when extension of FileUpLoads are not allowed

    - by Vy Clarks
    I have a asp FileUpload control in my aspx page. And the code behind to check file's extension and then insert them into database: private string Write(HttpPostedFile file, string table) { string fileNameMain = Path.GetFileName(file.FileName); // check for the valid file extension string fileExtension = Path.GetExtension(fileNameMain).ToLower(); if (fileExtension.Equals(".pdf") || fileExtension.Equals(".doc")) { ...insert fileupload into database } else { LabelError.Text = "Extension of files are not allowed."; return null; } } With the code above, it checks the extension and then show the message "Extension of files are not allowed." in a LabelError if the fileupload is not allowed. Now, I'm required to do the "check-extension" in the other way: at the moment the client click and choose FileUpload, an alert show "Extension of files are not allowed.". I need a way to make an alert show at the momment the FileUpload choosed in browser. Help!!!!

    Read the article

  • Sometimes can rename, remove a folder; sometimes cannot

    - by Vy Clarks
    In my website project. I need to rename or remove some folder by code. Sometimes I can do all of that, but sometimes I cannot with error: Access to the path is denied Try to find to solution on Google. May be, there are two reason: The permisstion of that Folder Some subFolder or some file in that Folder that's being held open. Try to check: Right click on Folder- Properties-- Security: if this is the right way to check the permission, the Folder allowes every action (read, write....) There are no file, no subfolder of that Folder is opened. Why? I still dont understant why sometimes I can rename folder but sometimes I cannot. Help!! I need your opinions!!! UPDATE: take a look at my code above: I want to rename the a folder with the new name inputed in a Textbox txtFilenFolderName: protected void btnUpdate_Click(object sender, EventArgs e) { string[] values = EditValue; string oldpath = values[0];// = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder" string oldName = values[2]; //= New Folder string newName = txtFilenFolderName.Text; //= New Folder1 string newPath = string.Empty; if (oldName != newName) { newPath = oldpath.Replace(oldName, newName); Directory.Move(oldpath, newPath); } else lblmessage2.Text = "New name must not be the same as the old "; } } Try to debug: oldpath = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder" oldName = New Folder newName= New Folder1 newpath = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder1" Everything seems right, but I when I click on buton Edit --- rename--- Update--- an error occur: Access to the path is denied D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder Help!

    Read the article

  • Building View Matrix in Direct3D11

    - by Balls
    Am I doing it right? I converted this. m_ViewMatrix = XMMatrixLookAtLH(XMLoadFloat3(&m_Position), lookAtVector, upVector); to this one. XMVECTOR vz = XMVector3Normalize( lookAtVector - XMLoadFloat3(&m_Position) ); XMVECTOR vx = XMVector3Normalize( XMVector3Cross( upVector, vz ) ); XMVECTOR vy = XMVector3Cross( vz, vx ); m_ViewMatrix.r[0] = vx; m_ViewMatrix.r[1] = vy; m_ViewMatrix.r[2] = vz; m_ViewMatrix.r[3] = XMLoadFloat3(&m_Position); m_ViewMatrix.r[0].m128_f32[3] = 0.0f; m_ViewMatrix.r[1].m128_f32[3] = 0.0f; m_ViewMatrix.r[2].m128_f32[3] = 0.0f; m_ViewMatrix.r[3].m128_f32[3] = 1.0f; m_ViewMatrix = XMMatrixInverse( &XMMatrixDeterminant(m_ViewMatrix), m_ViewMatrix ); Everything looks fine when I run it. Another question is, I saw on this site(http://webglfactory.blogspot.com/2011/06/how-to-create-view-matrix.html) that he subtracted lookat from position in his vector vz. I tried it but gave me wrong view matrix. Can anyone check my code. I'm studying linear algebra right now. Sucks my course doesn't have one. Thank you, Balls

    Read the article

  • Java : 2D Collision Detection

    - by neko
    I'm been working on 2D rectangle collision for weeks and still cannot get this problem fixed. The problem I'm having is how to adjust a player to obstacles when it collides. I'm referencing this link. The player sometime does not get adjusted to obstacles. Also, it sometimes stuck in obstacle guy after colliding. Here, the player and the obstacle are inheriting super class Sprite I can detect collision between the two rectangles and the point by ; public Point getSpriteCollision(Sprite sprite, double newX, double newY) { // set each rectangle Rectangle spriteRectA = new Rectangle( (int)getPosX(), (int)getPosY(), getWidth(), getHeight()); Rectangle spriteRectB = new Rectangle( (int)sprite.getPosX(), (int)sprite.getPosY(), sprite.getWidth(), sprite.getHeight()); // if a sprite is colliding with the other sprite if (spriteRectA.intersects(spriteRectB)){ System.out.println("Colliding"); return new Point((int)getPosX(), (int)getPosY()); } return null; } and to adjust sprites after a collision: // Update the sprite's conditions public void update() { // only the player is moving for simplicity // collision detection on x-axis (just x-axis collision detection at this moment) double newX = x + vx; // calculate the x-coordinate of sprite move Point sprite = getSpriteCollision(map.getSprite().get(1), newX, y);// collision coordinates (x,y) if (sprite == null) { // if the player is no colliding with obstacle guy x = newX; // move } else { // if collided if (vx > 0) { // if the player was moving from left to right x = (sprite.x - vx); // this works but a bit strange } else if (vx < 0) { x = (sprite.x + vx); // there's something wrong with this too } } vx=0; y+=vy; vy=0; } I think there is something wrong in update() but cannot fix it. Now I only have a collision with the player and an obstacle guy but in future, I'm planning to have more of them and making them all collide with each other. What would be a good way to do it? Thanks in advance.

    Read the article

  • Why does the player fall down when in between platforms? Tile based platformer

    - by inzombiak
    I've been working on a 2D platformer and have gotten the collision working, except for one tiny problem. My games a tile based platformer and whenever the player is in between two tiles, he falls down. Here is my code, it's fire off using an ENTER_FRAME event. It's only for collision from the bottom for now. var i:int; var j:int; var platform:Platform; var playerX:int = player.x/20; var playerY:int = player.y/20; var xLoopStart:int = (player.x - player.width)/20; var yLoopStart:int = (player.y - player.height)/20; var xLoopEnd:int = (player.x + player.width)/20; var yLoopEnd:int = (player.y + player.height)/20; var vy:Number = player.vy/20; var hitDirection:String; for(i = yLoopStart; i <= yLoopEnd; i++) { for(j = xLoopStart; j <= xLoopStart; j++) { if(platforms[i*36 + j] != null && platforms[i*36 + j] != 0) { platform = platforms[i*36 + j]; if(player.hitTestObject(platform) && i >= playerY) { hitDirection = "bottom"; } } } } This isn't the final version, going to replace hitTest with something more reliable , but this is an interesting problem and I'd like to know whats happening. Is my code just slow? Would firing off the code with a TIMER event fix it? Any information would be great.

    Read the article

1 2 3  | Next Page >