Search Results

Search found 3950 results on 158 pages for 'float'.

Page 6/158 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • How to remove the boundary effects arising due to zero padding in scipy/numpy fft?

    - by Omkar
    I have made a python code to smoothen a given signal using the Weierstrass transform, which is basically the convolution of a normalised gaussian with a signal. The code is as follows: #Importing relevant libraries from __future__ import division from scipy.signal import fftconvolve import numpy as np def smooth_func(sig, x, t= 0.002): N = len(x) x1 = x[-1] x0 = x[0] # defining a new array y which is symmetric around zero, to make the gaussian symmetric. y = np.linspace(-(x1-x0)/2, (x1-x0)/2, N) #gaussian centered around zero. gaus = np.exp(-y**(2)/t) #using fftconvolve to speed up the convolution; gaus.sum() is the normalization constant. return fftconvolve(sig, gaus/gaus.sum(), mode='same') If I run this code for say a step function, it smoothens the corner, but at the boundary it interprets another corner and smoothens that too, as a result giving unnecessary behaviour at the boundary. I explain this with a figure shown in the link below. Boundary effects This problem does not arise if we directly integrate to find convolution. Hence the problem is not in Weierstrass transform, and hence the problem is in the fftconvolve function of scipy. To understand why this problem arises we first need to understand the working of fftconvolve in scipy. The fftconvolve function basically uses the convolution theorem to speed up the computation. In short it says: convolution(int1,int2)=ifft(fft(int1)*fft(int2)) If we directly apply this theorem we dont get the desired result. To get the desired result we need to take the fft on a array double the size of max(int1,int2). But this leads to the undesired boundary effects. This is because in the fft code, if size(int) is greater than the size(over which to take fft) it zero pads the input and then takes the fft. This zero padding is exactly what is responsible for the undesired boundary effects. Can you suggest a way to remove this boundary effects? I have tried to remove it by a simple trick. After smoothening the function I am compairing the value of the smoothened signal with the original signal near the boundaries and if they dont match I replace the value of the smoothened func with the input signal at that point. It is as follows: i = 0 eps=1e-3 while abs(smooth[i]-sig[i])> eps: #compairing the signals on the left boundary smooth[i] = sig[i] i = i + 1 j = -1 while abs(smooth[j]-sig[j])> eps: # compairing on the right boundary. smooth[j] = sig[j] j = j - 1 There is a problem with this method, because of using an epsilon there are small jumps in the smoothened function, as shown below: jumps in the smooth func Can there be any changes made in the above method to solve this boundary problem?

    Read the article

  • What is causing these visual artifacts on my OpenGL sprites?

    - by Amplify91
    What could be the cause of the defects in my characters sprite? I am using OpenGL ES 2.0. I draw my sprites in a sprite batch that uses UV coordinates from one large texture atlas. If you look around the character' edges, you'll see two noticeable problems: The invisible alpha background is not invisible, but shows a strange static-like background. There are unwanted streaks where the character nears the edge of the frame (but only in some frames of the animation, this happened to be one of them). Any idea what could be causing these? I will provide related code if asked for, but I'll try to avoid just dumping the entire project and expecting someone to look through it all. EDIT: Here's a bit of code: This is how I generate my UV coordinates: private float[] createFrameUV(int frameWidth, int frameHeight, int x, int y){ float[] uv = new float[4]; if(numberOfFrames>1){ float width = (float)frameWidth / (float)mBitmap.getWidth(); float height = (float)frameHeight / (float)mBitmap.getHeight(); float u = (float)x / (float)mBitmap.getWidth(); float v = (float)y / (float)mBitmap.getHeight(); uv[0] = u; uv[1] = v; uv[2] = u + width; uv[3] = v + height; }else{ uv[0] = 0f; uv[1] = 0f; uv[2] = 1f; uv[3] = 1f; } return uv; } These are some OpenGL settings: GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);

    Read the article

  • How do I make a jumping dolphin rotate realistically?

    - by Johnny
    I want to program a dolphin that jumps and rotates like a real dolphin. Jumping is not the problem, but I don't know how to make the rotation. At the moment, my dolphin rotates a little weird. But I want that it rotates like a real dolphin does. How can I improve the rotation? public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D image, water; float Gravity = 5.0F; float Acceleration = 20.0F; Vector2 Position = new Vector2(1200,720); Vector2 Velocity; float rotation = 0; SpriteEffects flip; Vector2 Speed = new Vector2(0, 0); public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; } protected override void Initialize() { base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); image = Content.Load<Texture2D>("cartoondolphin"); water = Content.Load<Texture2D>("background"); flip = SpriteEffects.None; } protected override void Update(GameTime gameTime) { float VelocityX = 0f; float VelocityY = 0f; float time = (float)gameTime.ElapsedGameTime.TotalSeconds; KeyboardState kbState = Keyboard.GetState(); if(kbState.IsKeyDown(Keys.Left)) { rotation = 0; flip = SpriteEffects.None; VelocityX += -5f; } if(kbState.IsKeyDown(Keys.Right)) { rotation = 0; flip = SpriteEffects.FlipHorizontally; VelocityX += 5f; } // jump if the dolphin is under water if(Position.Y >= 670) { if (kbState.IsKeyDown(Keys.A)) { if (flip == SpriteEffects.None) { rotation += 0.01f; VelocityY += 40f; } else { rotation -= 0.01f; VelocityY += 40f; } } } else { if (flip == SpriteEffects.None) { rotation -= 0.01f; VelocityY += -10f; } else { rotation += 0.01f; VelocityY += -10f; } } float deltaY = 0; float deltaX = 0; deltaY = Gravity * (float)gameTime.ElapsedGameTime.TotalSeconds; deltaX += VelocityX * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration; deltaY += -VelocityY * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration; Speed = new Vector2(Speed.X + deltaX, Speed.Y + deltaY); Position += Speed * (float)gameTime.ElapsedGameTime.TotalSeconds; Velocity.X = 0; if (Position.Y + image.Height/2 > graphics.PreferredBackBufferHeight) Position.Y = graphics.PreferredBackBufferHeight - image.Height/2; base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(water, new Rectangle(0, graphics.PreferredBackBufferHeight -100, graphics.PreferredBackBufferWidth, 100), Color.White); spriteBatch.Draw(image, Position, null, Color.White, rotation, new Vector2(image.Width / 2, image.Height / 2), 1, flip, 1); spriteBatch.End(); base.Draw(gameTime); } } I changed my code a little. But I still have some trouble with the rotation. Here's the entire code. The dolphin looks at the wrong direction if I press the left or right key. For example, it looks down if I press the left key. What is wrong with the rotation? At the beginning, the dolphin looks at the left side, but after I pressed a key it just looks down or up. I deleted the "rotation += 0.01f;" lines in the code. Is that correct? public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D image, water; float Gravity = 5.0F; float Acceleration = 20.0F; Vector2 Position = new Vector2(1200,720); Vector2 Velocity; float rotation = 0; SpriteEffects flip; Vector2 Speed = new Vector2(0, 0); Vector2 prevPos; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; } protected override void Initialize() { base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); image = Content.Load<Texture2D>("cartoondolphin"); water = Content.Load<Texture2D>("background"); flip = SpriteEffects.None; } protected override void Update(GameTime gameTime) { float VelocityX = 0f; float VelocityY = 0f; float time = (float)gameTime.ElapsedGameTime.TotalSeconds; KeyboardState kbState = Keyboard.GetState(); if(kbState.IsKeyDown(Keys.Left)) { flip = SpriteEffects.None; VelocityX += -5f; } if(kbState.IsKeyDown(Keys.Right)) { flip = SpriteEffects.FlipHorizontally; VelocityX += 5f; } rotation = (float)Math.Atan2(Position.X - prevPos.X, Position.Y - prevPos.Y); prevPos = Position; // jump if the dolphin is under water if(Position.Y >= 670) { if (kbState.IsKeyDown(Keys.A)) { if (flip == SpriteEffects.None) { VelocityY += 40f; } else { VelocityY += 40f; } } } else { if (flip == SpriteEffects.None) { VelocityY += -10f; } else { VelocityY += -10f; } } float deltaY = 0; float deltaX = 0; deltaY = Gravity * (float)gameTime.ElapsedGameTime.TotalSeconds; deltaX += VelocityX * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration; deltaY += -VelocityY * (float)gameTime.ElapsedGameTime.TotalSeconds * Acceleration; Speed = new Vector2(Speed.X + deltaX, Speed.Y + deltaY); Position += Speed * (float)gameTime.ElapsedGameTime.TotalSeconds; Velocity.X = 0; if (Position.Y + image.Height/2 > graphics.PreferredBackBufferHeight) Position.Y = graphics.PreferredBackBufferHeight - image.Height/2; base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(water, new Rectangle(0, graphics.PreferredBackBufferHeight -100, graphics.PreferredBackBufferWidth, 100), Color.White); spriteBatch.Draw(image, Position, null, Color.White, rotation, new Vector2(image.Width / 2, image.Height / 2), 1, flip, 1); spriteBatch.End(); base.Draw(gameTime); } }

    Read the article

  • Changes to data inside class not being shown when accessed from outside class.

    - by Hypatia
    I have two classes, Car and Person. Car has as one of its members an instance of Person, driver. I want to move a car, while keeping track of its location, and also move the driver inside the car and get its location. However, while this works from inside the class (I have printed out the values as they are calculated), when I try to access the data from main, there's nothing there. I.e. the array position[] ends up empty. I am wondering if there is something wrong with the way I have set up the classes -- could it be a problem of the scope of the object? I have tried simplifying the code so that I only give what is necessary. Hopefully that covers everything that you would need to see. The constructer Car() fills the offset array of driver with nonzero values. class Car{ public: Container(float=0,float=0,float=0); ~Container(); void move(float); void getPosition(float[]); void getDriverPosition(float[]); private: float position[3]; Person driver; float heading; float velocity; }; class Person{ public: Person(float=0,float=0,float=0); ~Person(); void setOffset(float=0,float=0,float=0); void setPosition(float=0,float=0,float=0); void getOffset(float[]); void getPosition(float[]); private: float position[3]; float offset[3]; }; Some of the functions: void Car::move(float time){ float distance = velocity*time; location[0] += distance*cos(PI/2 - heading); location[1] += distance*sin(PI/2 - heading); float driverLocation [3]; float offset[3]; driver->getOffset(offset); for (int i = 0; i < 3; i++){ driverLocation[i] = offset[i] + location[i]; } } void Car::getDriverPosition(float p[]){ driver.getPosition(p); } void Person::getPosition(float p[]){ for (int i = 0; i < 3; i++){ p[i] = position[i]; } } void Person::getOffset(float o[]){ for (int i = 0; i < 3; i++){ o[i] = offset[i]; } } In Main: Car * car = new Car(); car->move(); float p[3]; car->getDriverPosition(p); When I print driverLocation[] inside the move() function, I have actual nonzero values. When I print p[] inside main, all I get are zeros.

    Read the article

  • Why does division yield a vastly different result than multiplication by a fraction in floating points.

    - by Avram
    I understand why floating point numbers can't be compared, and know about the mantissa and exponent binary representation, but I'm no expert and today I came across something I don't get: Namely lets say you have something like: float denominator, numerator, resultone, resulttwo; resultone = numerator / denominator; float buff = 1 / denominator; resulttwo = numerator * buff; To my knowledge different flops can yield different results and this is not unusual. But in some edge cases these two results seem to be vastly different. To be more specific in my GLSL code calculating the Beckmann facet slope distribution for the Cook-Torrance lighitng model: float a = 1 / (facetSlopeRMS * facetSlopeRMS * pow(clampedCosHalfNormal, 4)); float b = clampedCosHalfNormal * clampedCosHalfNormal - 1.0; float c = facetSlopeRMS * facetSlopeRMS * clampedCosHalfNormal * clampedCosHalfNormal; facetSlopeDistribution = a * exp(b/c); yields very very different results to float a = (facetSlopeRMS * facetSlopeRMS * pow(clampedCosHalfNormal, 4)); facetDlopeDistribution = exp(b/c) / a; Why does it? The second form of the expression is problematic. If I say try to add the second form of the expression to a color I get blacks, even though the expression should always evaluate to a positive number. Am I getting an infinity? A NaN? if so why?

    Read the article

  • GLSL: How Do I cast a float into an int?

    - by dugla
    In a GLSL fragment shader I am trying to cast a float into an int. The compiler has other ideas. It complains thusly: ERROR: 0:60: '=' : cannot convert from 'mediump float' to 'highp int' I am trying to do this: mediump float indexf = floor(2.0 * mixer); highp int index = indexf; I (vainly) tried to raise the precision of the int above the float to appease the GL Gods but no joy. Could someone please school me here? Thanks, Doug

    Read the article

  • Convert ieee 754 float to hex with c - printf

    - by Michael
    Ideally the following code would take a float in IEEE 754 representation and convert it into hexadecimal void convert() //gets the float input from user and turns it into hexadecimal { float f; printf("Enter float: "); scanf("%f", &f); printf("hex is %x", f); } I'm not too sure what's going wrong. It's converting the number into a hexadecimal number, but a very wrong one. 123.1443 gives 40000000 43.3 gives 60000000 8 gives 0 so it's doing something, I'm just not too sure what. Help would be appreciated

    Read the article

  • Why won't Silverlight handle the conversion of my custom float property

    - by Jeff Weber
    In a Silverlight 4 project I have a class that extends Canvas: public class AppendageCanvas : Canvas { public float Friction { get; set; } public float Restitution { get; set; } public float Density { get; set; } } I use this canvas in Blend by dragging it onto another control and setting the custom properties: When I run the app, I get the following error when InitializeComponent is called on the control containing my custom canvas: I'm not sure why Silverlight isn't able to convert this property from it's string representation in Xaml, to the float that it is. Anyone have any ideas?

    Read the article

  • Casting problem cant convert from void to float C++

    - by Makenshi
    as i said i get this horrible error i dont really know what to do anymore float n= xAxis[i].Normalize(); thats where i get the error and i get it cuz normalize is a void function this is it void CVector::normalize() { float len=Magnitude(); this->x /= len; this->y /= len; } i need normalize to stay as void tho i tried normal casting like this float n= (float)xAxis[i].Normalize(); and it doesnt work also with static,dynamic cast,reinterpret,const cast and cant make it work any help would be really apreciated... thank you .<

    Read the article

  • Use Margin Auto and Center to center Float Left Div

    - by Yan Cheng CHEOK
    I know this question had been asked many times. http://stackoverflow.com/questions/1740587/float-a-div-to-center However, I follow their suggestion : <center> <div style="margin : auto"> <a href="#" style="float: left; margin-right: 10px;">Menu Item 1</a> <a href="#" style="float: left; margin-right: 10px;">Menu Item 2</a> <a href="#" style="float: left; margin-right: 10px;">Menu Item 3</a> </div> </center> By using "Center" and "Margin Auto", I still unable to center the menu item.

    Read the article

  • template function roundTo int, float -> truncation

    - by Oops
    Hi, according to this question: http://stackoverflow.com/questions/2833730/calling-template-function-without-type-inference the round function I will use in the future now looks like: template < typename TOut, typename TIn > TOut roundTo( TIn value ) { return static_cast<TOut>( value + 0.5 ); } double d = 1.54; int i = rountTo<int>(d); However it makes sense only if it will be used to round to integral datatypes like char, short, int, long, long long int, and it's unsigned counterparts. If it ever will be used with a TOut As float or long double it will deliver s***. double d = 1.54; float f = roundTo<float>(d); // aarrrgh now float is 2.04; I was thinking of a specified overload of the function but ... that's not possible... How would you solve this problem? many thanks in advance Oops

    Read the article

  • remove/ignore float from outer div

    - by acidzombie24
    This may sound weird but i have some css which aligns mys divs. In one place i also use http://www.brunildo.org/test/img_center.html which centers images. Now i want my divs inside a larger div to go to another line if this one gets full. float: left seems to be the answer. The problem is it ruins my formatting. Including solution in the above link. I have this test code. If i remove the width and float it looks fine except it may take up too much space and not go to another line. I was thinking i could use float on an outerdiv and center the image within. However float: left is still breaking it. I am hoping there is a way to remove the float so each div does go left but the div inside centers correctly not breaking my formatting. <style type="text/css"> .wraptocenter { display: table-cell; text-align: center; vertical-align: middle; width: 200px; height: 200px; background: blue; } .wraptocenter * { vertical-align: middle; } /*\*//*/ .wraptocenter { display: block; } .wraptocenter span { display: inline-block; height: 100%; width: 1px; } /**/ div.c { background: red; overflow: hidden; min-width: 400px; max-width: 400px; } div.c div { float: left; } </style> <!--[if lt IE 8]><style> .wraptocenter span { display: inline-block; height: 100%; } </style><![endif]--> <div class="c"> <div> <div> <div class="wraptocenter"><span></span><img src="a.jpg" alt="/a.jpg"></div> <div class="wraptocenter"><span></span><img src="a.jpg" alt="/a.jpg"></div> <div class="wraptocenter"><span></span><img src="a.jpg" alt="/a.jpg"></div> </div></div></div>

    Read the article

  • Parsing a string representing a float *with an exponent* in Python

    - by Lucas
    Hi, I have a large file with numbers in the form of 6,52353753563E-7. So there's an exponent in that string. float() dies on this. While I could write custom code to pre-process the string into something float() can eat, I'm looking for the pythonic way of converting these into a float (something like a format string passed somewhere). I must say I'm surprised float() can't handle strings with such an exponent, this is pretty common stuff. I'm using python 2.6, but 3.1 is an option if need be.

    Read the article

  • add two float values in java

    - by user1845286
    acually i try to add two float values in java like this import java.text.DecimalFormat; class ExactDecimalValue { final strictfp static public void main(String... arg) { float f1=123.00000f; float f2=124.00000f; float f3=f1+f2; System.out.println(f1+f2); System.out.println("sum of two floats:"+f3); /*my expected output is:247.00000 but comming output is:247.0 and 247*/ } } Now what i can do to get the value in this format:247.00000. please any one help me. Thanks & Regards venkatesh

    Read the article

  • Computing "average" of two colors

    - by Francisco P.
    This is only marginally programming related - has much more to do w/ colors and their representation. I am working on a very low level app. I have an array of bytes in memory. Those are characters. They were rendered with anti-aliasing: they have values from 0 to 255, 0 being fully transparent and 255 totally opaque (alpha, if you wish). I am having trouble conceiving an algorithm for the rendering of this font. I'm doing the following for each pixel: // intensity is the weight I talked about: 0 to 255 intensity = glyphs[text[i]][x + GLYPH_WIDTH*y]; if (intensity == 255) continue; // Don't draw it, fully transparent else if (intensity == 0) setPixel(x + xi, y + yi, color, base); // Fully opaque, can draw original color else { // Here's the tricky part // Get the pixel in the destination for averaging purposes pixel = getPixel(x + xi, y + yi, base); // transfer is an int for calculations transfer = (int) ((float)((float) (255.0 - (float) intensity/255.0) * (float) color.red + (float) pixel.red)/2); // This is my attempt at averaging newPixel.red = (Byte) transfer; transfer = (int) ((float)((float) (255.0 - (float) intensity/255.0) * (float) color.green + (float) pixel.green)/2); newPixel.green = (Byte) transfer; // transfer = (int) ((float) ((float) 255.0 - (float) intensity)/255.0 * (((float) color.blue) + (float) pixel.blue)/2); transfer = (int) ((float)((float) (255.0 - (float) intensity/255.0) * (float) color.blue + (float) pixel.blue)/2); newPixel.blue = (Byte) transfer; // Set the newpixel in the desired mem. position setPixel(x+xi, y+yi, newPixel, base); } The results, as you can see, are less than desirable. That is a very zoomed in image, at 1:1 scale it looks like the text has a green "aura". Any idea for how to properly compute this would be greatly appreciated. Thanks for your time!

    Read the article

  • Curl Wrapper Class does not return any data even though it worked previously?

    - by Scott Faisal
    We changed servers and installed all necessary software and just cannot seem to pin point what is going on. A simple CURL request does not return anything. Command Line CURL commands work just fine. We are using a wrapper for CURL utilizing streams. Do PHP streams require any out of the ordinary configuration? We are using the latest Lamp stack. This is the var_dump: object(cURL_Response)#180 (14) { ["cURL:private"]= resource(288) of type (curl) ["data_stream:private"]= object(elTempStream)#178 (1) { ["fp"]= resource(290) of type (stream) } ["request_header:private"]= NULL ["response_header:private"]= object(cURL_Headers)#179 (1) { ["headers:private"]= string(0) "" } ["response_headers:private"]= array(1) { [0]= object(cURL_Headers)#179 (1) { ["headers:private"]= string(0) "" } } ["error:private"]= string(0) "" ["errno:private"]= int(0) ["info:private"]= array(21) { ["url"]= string(21) "http://www.yahoo.com/" ["content_type"]= string(23) "text/html;charset=utf-8" ["http_code"]= int(200) ["header_size"]= int(1195) ["request_size"]= int(1153) ["filetime"]= int(-1) ["ssl_verify_result"]= int(0) ["redirect_count"]= int(1) ["total_time"]= float(0.486924) ["namelookup_time"]= float(0.003692) ["connect_time"]= float(0.005709) ["pretransfer_time"]= float(0.005714) ["size_upload"]= float(0) ["size_download"]= float(28509) ["speed_download"]= float(58549) ["speed_upload"]= float(0) ["download_content_length"]= float(211) ["upload_content_length"]= float(0) ["starttransfer_time"]= float(0.149365) ["redirect_time"]= float(0.312743) ["request_header"]= string(973) "GET / HTTP/1.0 User-Agent: cURL_ClientBase (PHP v/5.2.6-1+lenny4) Host: www.yahoo.com Accept: / Accept-Encoding: gzip, deflate, compress Referer: http://yahoo.com Cookie: B=e5iber15t7u05&b=3&s=ie; fpc_s=d=GGX6WCTIR29HWsjgLxFejKc_YJWxRqm3jYdEd6lu7W5ophpuAHBm6JGtNvhv97anG4VtaIMHQBPg3JAMOZGq59Lz_tRn_TFXgUT8T_at5HdCktVJLycy&v=2; fpt=d=nt1OT7HPe9wVIkHbMkpzQOgbP3.mQ3o1SPX7k5ztrFrWeeSWK5IgQooRY.8KtTeRMiaSEZ0kv3sO1MWtEsAzjVlRCDAZBoxqOs17v6PaZbPRqmDc92ivoMia.CqjufRs4_guOO4AyhRZ7_ml8rzxFrYeexpR2jLN0oPMyEWT0nbEf6Sdf._Bkh0HMfmI7KBnEx5uZBEEmV.wTfGRLG7zSd9sA4itOFv.r6AjP39CnogSn7NTJnqg_kEcKoiCM.lR5w_MqMc8IgWMBgSAZZgGEZpfmvxlQGnUzPwNh2pSpTe2wxFS3v1zPopDgoo2VsO3uzeyA3A_j7Hlk1P8T08DHbfr6ApDMUcr7d0QIt4pGYIxVV45XzfgpT7mgUdMei6VZrD9ozVQF0oqxrs1Ufri.XzPdB3NdQ--&v=1; fpc=d=sRPCfUfBTW96.RGiQn4hSkfi3p7WnPCAqYl5YoHecI7zjg7gH7PolscoPcq1Esm8dR.Rg1.AbQCpo2WBPXn1St96PpcjeCC.pj2.Upb3mKSRQkYPIVP1vQcL9nL7J8s9Z0VIXjiBFgSUcxyzDeUdP4us2YbVO3PbaVIwaIEfFsX3WI7YgiTbkrTGtwnFgoSYq6l8tnw-&v=2" } ["info_flagged:private"]= array(20) { [1048577]= string(21) "http://www.yahoo.com/" [2097154]= int(200) [2097166]= int(-1) [3145731]= float(0.486924) [3145732]= float(0.003692) [3145733]= float(0.005709) [3145734]= float(0.005714) [3145745]= float(0.149365) [3145747]= float(0.312743) [3145735]= float(0) [3145736]= float(28509) [3145737]= float(58549) [3145738]= float(0) [2097163]= int(1195) [2]= string(973) "GET / HTTP/1.0 User-Agent: cURL_ClientBase (PHP v/5.2.6-1+lenny4) Host: www.yahoo.com Accept: / Accept-Encoding: gzip, deflate, compress Referer: http://yahoo.com Cookie: B=e5iber15t7u05&b=3&s=ie; fpc_s=d=GGX6WCTIR29HWsjgLxFejKc_YJWxRqm3jYdEd6lu7W5ophpuAHBm6JGtNvhv97anG4VtaIMHQBPg3JAMOZGq59Lz_tRn_TFXgUT8T_at5HdCktVJLycy&v=2; fpt=d=nt1OT7HPe9wVIkHbMkpzQOgbP3.mQ3o1SPX7k5ztrFrWeeSWK5IgQooRY.8KtTeRMiaSEZ0kv3sO1MWtEsAzjVlRCDAZBoxqOs17v6PaZbPRqmDc92ivoMia.CqjufRs4_guOO4AyhRZ7_ml8rzxFrYeexpR2jLN0oPMyEWT0nbEf6Sdf._Bkh0HMfmI7KBnEx5uZBEEmV.wTfGRLG7zSd9sA4itOFv.r6AjP39CnogSn7NTJnqg_kEcKoiCM.lR5w_MqMc8IgWMBgSAZZgGEZpfmvxlQGnUzPwNh2pSpTe2wxFS3v1zPopDgoo2VsO3uzeyA3A_j7Hlk1P8T08DHbfr6ApDMUcr7d0QIt4pGYIxVV45XzfgpT7mgUdMei6VZrD9ozVQF0oqxrs1Ufri.XzPdB3NdQ--&v=1; fpc=d=sRPCfUfBTW96.RGiQn4hSkfi3p7WnPCAqYl5YoHecI7zjg7gH7PolscoPcq1Esm8dR.Rg1.AbQCpo2WBPXn1St96PpcjeCC.pj2.Upb3mKSRQkYPIVP1vQcL9nL7J8s9Z0VIXjiBFgSUcxyzDeUdP4us2YbVO3PbaVIwaIEfFsX3WI7YgiTbkrTGtwnFgoSYq6l8tnw-&v=2" [2097164]= int(1153) [2097165]= int(0) [3145743]= float(211) [3145744]= float(0) [1048594]= string(23) "text/html;charset=utf-8" } ["request_url:private"]= string(16) "http://yahoo.com" ["response_url:private"]= string(21) "http://www.yahoo.com/" ["status_code:private"]= int(200) ["cookies:private"]= array(0) { } ["request_headers"]= string(973) "GET / HTTP/1.0 User-Agent: cURL_ClientBase (PHP v/5.2.6-1+lenny4) Host: www.yahoo.com Accept: / Accept-Encoding: gzip, deflate, compress Referer: http://yahoo.com Cookie: B=e5iber15t7u05&b=3&s=ie; fpc_s=d=GGX6WCTIR29HWsjgLxFejKc_YJWxRqm3jYdEd6lu7W5ophpuAHBm6JGtNvhv97anG4VtaIMHQBPg3JAMOZGq59Lz_tRn_TFXgUT8T_at5HdCktVJLycy&v=2; fpt=d=nt1OT7HPe9wVIkHbMkpzQOgbP3.mQ3o1SPX7k5ztrFrWeeSWK5IgQooRY.8KtTeRMiaSEZ0kv3sO1MWtEsAzjVlRCDAZBoxqOs17v6PaZbPRqmDc92ivoMia.CqjufRs4_guOO4AyhRZ7_ml8rzxFrYeexpR2jLN0oPMyEWT0nbEf6Sdf._Bkh0HMfmI7KBnEx5uZBEEmV.wTfGRLG7zSd9sA4itOFv.r6AjP39CnogSn7NTJnqg_kEcKoiCM.lR5w_MqMc8IgWMBgSAZZgGEZpfmvxlQGnUzPwNh2pSpTe2wxFS3v1zPopDgoo2VsO3uzeyA3A_j7Hlk1P8T08DHbfr6ApDMUcr7d0QIt4pGYIxVV45XzfgpT7mgUdMei6VZrD9ozVQF0oqxrs1Ufri.XzPdB3NdQ--&v=1; fpc=d=sRPCfUfBTW96.RGiQn4hSkfi3p7WnPCAqYl5YoHecI7zjg7gH7PolscoPcq1Esm8dR.Rg1.AbQCpo2WBPXn1St96PpcjeCC.pj2.Upb3mKSRQkYPIVP1vQcL9nL7J8s9Z0VIXjiBFgSUcxyzDeUdP4us2YbVO3PbaVIwaIEfFsX3WI7YgiTbkrTGtwnFgoSYq6l8tnw-&v=2" }

    Read the article

  • Internet Explorer 6 and 7: floated elements expand to 100% width when they contain a child element f

    - by Paul D. Waite
    I've got a parent div floated left, with two child divs that I need to float right. The parent div should (if I understand the spec correctly) be as wide as needed to contain the child divs, and this is how it behaves in Firefox et al. In IE, the parent div expands to 100% width. This seems to be an issue with floated elements that have children floated right. Test page: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>Float test</title> </head> <body> <div style="border-top:solid 10px #0c0;float:left;"> <div style="border-top:solid 10px #00c;float:right;">Tester 1</div> <div style="border-top:solid 10px #c0c;float:right;">Tester 2</div> </div> </body> </html> Unfortunately I can't fix the width of the child divs, so I can't set a fixed width on the parent. Is there a CSS-only workaround to make the parent div as wide as the child divs?

    Read the article

  • Converting 2D Physics to 3D.

    - by static void main
    I'm new to game physics and I am trying to adapt a simple 2D ball simulation for a 3D simulation with the Java3D library. I have this problem: Two things: 1) I noted down the values generated by the engine: X/Y are too high and minX/minY/maxY/maxX values are causing trouble. Sometimes the balls are drawing but not moving Sometimes they are going out of the panel Sometimes they're moving on little area Sometimes they just stick at one place... 2) I'm unable to select/define/set the default correct/suitable values considering the 3D graphics scaling/resolution while they are set with respect to 2D screen coordinates, that is my only problem. Please help. This is the code: public class Ball extends GameObject { private float x, y; // Ball's center (x, y) private float speedX, speedY; // Ball's speed per step in x and y private float radius; // Ball's radius // Collision detected by collision detection and response algorithm? boolean collisionDetected = false; // If collision detected, the next state of the ball. // Otherwise, meaningless. private float nextX, nextY; private float nextSpeedX, nextSpeedY; private static final float BOX_WIDTH = 640; private static final float BOX_HEIGHT = 480; /** * Constructor The velocity is specified in polar coordinates of speed and * moveAngle (for user friendliness), in Graphics coordinates with an * inverted y-axis. */ public Ball(String name1,float x, float y, float radius, float speed, float angleInDegree, Color color) { this.x = x; this.y = y; // Convert velocity from polar to rectangular x and y. this.speedX = speed * (float) Math.cos(Math.toRadians(angleInDegree)); this.speedY = speed * (float) Math.sin(Math.toRadians(angleInDegree)); this.radius = radius; } public void move() { if (collisionDetected) { // Collision detected, use the values computed. x = nextX; y = nextY; speedX = nextSpeedX; speedY = nextSpeedY; } else { // No collision, move one step and no change in speed. x += speedX; y += speedY; } collisionDetected = false; // Clear the flag for the next step } public void collideWith() { // Get the ball's bounds, offset by the radius of the ball float minX = 0.0f + radius; float minY = 0.0f + radius; float maxX = 0.0f + BOX_WIDTH - 1.0f - radius; float maxY = 0.0f + BOX_HEIGHT - 1.0f - radius; double gravAmount = 0.9811111f; double gravDir = (90 / 57.2960285258); // Try moving one full step nextX = x + speedX; nextY = y + speedY; System.out.println("In serializedBall in collision."); // If collision detected. Reflect on the x or/and y axis // and place the ball at the point of impact. if (speedX != 0) { if (nextX > maxX) { // Check maximum-X bound collisionDetected = true; nextSpeedX = -speedX; // Reflect nextSpeedY = speedY; // Same nextX = maxX; nextY = (maxX - x) * speedY / speedX + y; // speedX non-zero } else if (nextX < minX) { // Check minimum-X bound collisionDetected = true; nextSpeedX = -speedX; // Reflect nextSpeedY = speedY; // Same nextX = minX; nextY = (minX - x) * speedY / speedX + y; // speedX non-zero } } // In case the ball runs over both the borders. if (speedY != 0) { if (nextY > maxY) { // Check maximum-Y bound collisionDetected = true; nextSpeedX = speedX; // Same nextSpeedY = -speedY; // Reflect nextY = maxY; nextX = (maxY - y) * speedX / speedY + x; // speedY non-zero } else if (nextY < minY) { // Check minimum-Y bound collisionDetected = true; nextSpeedX = speedX; // Same nextSpeedY = -speedY; // Reflect nextY = minY; nextX = (minY - y) * speedX / speedY + x; // speedY non-zero } } speedX += Math.cos(gravDir) * gravAmount; speedY += Math.sin(gravDir) * gravAmount; } public float getSpeed() { return (float) Math.sqrt(speedX * speedX + speedY * speedY); } public float getMoveAngle() { return (float) Math.toDegrees(Math.atan2(speedY, speedX)); } public float getRadius() { return radius; } public float getX() { return x; } public float getY() { return y; } public void setX(float f) { x = f; } public void setY(float f) { y = f; } } Here's how I'm drawing the balls: public class 3DMovingBodies extends Applet implements Runnable { private static final int BOX_WIDTH = 800; private static final int BOX_HEIGHT = 600; private int currentNumBalls = 1; // number currently active private volatile boolean playing; private long mFrameDelay; private JFrame frame; private int currentFrameRate; private Ball[] ball = new Ball[currentNumBalls]; private Random rand; private Sphere[] sphere = new Sphere[currentNumBalls]; private Transform3D[] trans = new Transform3D[currentNumBalls]; private TransformGroup[] objTrans = new TransformGroup[currentNumBalls]; public 3DMovingBodies() { rand = new Random(); float angleInDegree = rand.nextInt(360); setLayout(new BorderLayout()); GraphicsConfiguration config = SimpleUniverse .getPreferredConfiguration(); Canvas3D c = new Canvas3D(config); add("Center", c); ball[0] = new Ball(0.5f, 0.0f, 0.5f, 0.4f, angleInDegree, Color.yellow); // ball[1] = new Ball(1.0f, 0.0f, 0.25f, 0.8f, angleInDegree, // Color.yellow); // ball[2] = new Ball(0.0f, 1.0f, 0.15f, 0.11f, angleInDegree, // Color.yellow); trans[0] = new Transform3D(); // trans[1] = new Transform3D(); // trans[2] = new Transform3D(); sphere[0] = new Sphere(0.5f); // sphere[1] = new Sphere(0.25f); // sphere[2] = new Sphere(0.15f); // Create a simple scene and attach it to the virtual universe BranchGroup scene = createSceneGraph(); SimpleUniverse u = new SimpleUniverse(c); u.getViewingPlatform().setNominalViewingTransform(); u.addBranchGraph(scene); startSimulation(); } public BranchGroup createSceneGraph() { // Create the root of the branch graph BranchGroup objRoot = new BranchGroup(); for (int i = 0; i < currentNumBalls; i++) { // Create a simple shape leaf node, add it to the scene graph. objTrans[i] = new TransformGroup(); objTrans[i].setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); Transform3D pos1 = new Transform3D(); pos1.setTranslation(randomPos()); objTrans[i].setTransform(pos1); objTrans[i].addChild(sphere[i]); objRoot.addChild(objTrans[i]); } BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); Color3f light1Color = new Color3f(1.0f, 0.0f, 0.2f); Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f); DirectionalLight light1 = new DirectionalLight(light1Color, light1Direction); light1.setInfluencingBounds(bounds); objRoot.addChild(light1); // Set up the ambient light Color3f ambientColor = new Color3f(1.0f, 1.0f, 1.0f); AmbientLight ambientLightNode = new AmbientLight(ambientColor); ambientLightNode.setInfluencingBounds(bounds); objRoot.addChild(ambientLightNode); return objRoot; } public void startSimulation() { playing = true; Thread t = new Thread(this); t.start(); } public void stop() { playing = false; } public void run() { long previousTime = System.currentTimeMillis(); long currentTime = previousTime; long elapsedTime; long totalElapsedTime = 0; int frameCount = 0; while (true) { currentTime = System.currentTimeMillis(); elapsedTime = (currentTime - previousTime); // elapsed time in // seconds totalElapsedTime += elapsedTime; if (totalElapsedTime > 1000) { currentFrameRate = frameCount; frameCount = 0; totalElapsedTime = 0; } for (int i = 0; i < currentNumBalls; i++) { ball[i].move(); ball[i].collideWith(); drawworld(); } try { Thread.sleep(88); } catch (Exception e) { e.printStackTrace(); } previousTime = currentTime; frameCount++; } } public void drawworld() { for (int i = 0; i < currentNumBalls; i++) { printTG(objTrans[i], "SteerTG"); trans[i].setTranslation(new Vector3f(ball[i].getX(), ball[i].getY(), 0.0f)); objTrans[i].setTransform(trans[i]); } } private Vector3f randomPos() /* * Return a random position vector. The numbers are hardwired to be within * the confines of the box. */ { Vector3f pos = new Vector3f(); pos.x = rand.nextFloat() * 5.0f - 2.5f; // -2.5 to 2.5 pos.y = rand.nextFloat() * 2.0f + 0.5f; // 0.5 to 2.5 pos.z = rand.nextFloat() * 5.0f - 2.5f; // -2.5 to 2.5 return pos; } // end of randomPos() public static void main(String[] args) { System.out.println("Program Started"); 3DMovingBodiesbb = new 3DMovingBodies(); bb.addKeyListener(bb); MainFrame mf = new MainFrame(bb, 600, 400); } }

    Read the article

  • IE7 and IE8: Float clearing without adding empty elements

    - by tk-421
    Hello, I'm having a problem similar to the one described here (without a resolution): http://stackoverflow.com/questions/2467745/ie7-float-and-clear-on-the-same-element The following HTML renders as intended in Firefox but not in (both) IE7 and IE8: <html> <head> <style> ul { list-style-type: none; } li { clear: both; padding: 5px; } .left { clear: left; float: left; } .middle { clear: none; float: left; } .right { clear: right; float: left; } </style> </head> <body> <ul> <li>1</li> <li class="left">2</li> <li class="right">3</li> <li class="left">4</li> <li class="middle">5</li> <li class="right">6</li> <li>7</li> </ul> </body> </html> This is a form layout, and in Firefox the results appear like: 1 2 3 4 5 6 7 That's what I'm going for. In IE7 and IE8 however, the results are: 1 2 3 5 6 4 7 [Note: I don't want to float anything to the right because I want the fields on my form to left-align correctly, without a giant space in-between the floated fields to account for the parent container's width.] Apparently I need a full clear, and can probably add an empty list-item element to the list to force clearing, but that seems like a dumb solution and sort of defeats the purpose. Any ideas? I've spent a few hours reading and trying different options without success.

    Read the article

  • OBJ model loaded in LWJGL has a black area with no texture

    - by gambiting
    I have a problem with loading an .obj file in LWJGL and its textures. The object is a tree(it's a paid model from TurboSquid, so I can't post it here,but here's the link if you want to see how it should look like): http://www.turbosquid.com/FullPreview/Index.cfm/ID/701294 I wrote a custom OBJ loader using the LWJGL tutorial from their wiki. It looks like this: public class OBJLoader { public static Model loadModel(File f) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(f)); Model m = new Model(); String line; Texture currentTexture = null; while((line=reader.readLine()) != null) { if(line.startsWith("v ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); float z = Float.valueOf(line.split(" ")[3]); m.verticies.add(new Vector3f(x,y,z)); }else if(line.startsWith("vn ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); float z = Float.valueOf(line.split(" ")[3]); m.normals.add(new Vector3f(x,y,z)); }else if(line.startsWith("vt ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); m.texVerticies.add(new Vector2f(x,y)); }else if(line.startsWith("f ")) { Vector3f vertexIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[0]), Float.valueOf(line.split(" ")[2].split("/")[0]), Float.valueOf(line.split(" ")[3].split("/")[0])); Vector3f textureIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[1]), Float.valueOf(line.split(" ")[2].split("/")[1]), Float.valueOf(line.split(" ")[3].split("/")[1])); Vector3f normalIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[2]), Float.valueOf(line.split(" ")[2].split("/")[2]), Float.valueOf(line.split(" ")[3].split("/")[2])); m.faces.add(new Face(vertexIndicies,textureIndicies,normalIndicies,currentTexture.getTextureID())); }else if(line.startsWith("g ")) { if(line.length()>2) { String name = line.split(" ")[1]; currentTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/" + name + ".png")); System.out.println(currentTexture.getTextureID()); } } } reader.close(); System.out.println(m.verticies.size() + " verticies"); System.out.println(m.normals.size() + " normals"); System.out.println(m.texVerticies.size() + " texture coordinates"); System.out.println(m.faces.size() + " faces"); return m; } } Then I create a display list for my model using this code: objectDisplayList = GL11.glGenLists(1); GL11.glNewList(objectDisplayList, GL11.GL_COMPILE); Model m = null; try { m = OBJLoader.loadModel(new File("res/untitled4.obj")); } catch (Exception e1) { e1.printStackTrace(); } int currentTexture=0; for(Face face: m.faces) { if(face.texture!=currentTexture) { currentTexture = face.texture; GL11.glBindTexture(GL11.GL_TEXTURE_2D, currentTexture); } GL11.glColor3f(1f, 1f, 1f); GL11.glBegin(GL11.GL_TRIANGLES); Vector3f n1 = m.normals.get((int) face.normal.x - 1); GL11.glNormal3f(n1.x, n1.y, n1.z); Vector2f t1 = m.texVerticies.get((int) face.textures.x -1); GL11.glTexCoord2f(t1.x, t1.y); Vector3f v1 = m.verticies.get((int) face.vertex.x - 1); GL11.glVertex3f(v1.x, v1.y, v1.z); Vector3f n2 = m.normals.get((int) face.normal.y - 1); GL11.glNormal3f(n2.x, n2.y, n2.z); Vector2f t2 = m.texVerticies.get((int) face.textures.y -1); GL11.glTexCoord2f(t2.x, t2.y); Vector3f v2 = m.verticies.get((int) face.vertex.y - 1); GL11.glVertex3f(v2.x, v2.y, v2.z); Vector3f n3 = m.normals.get((int) face.normal.z - 1); GL11.glNormal3f(n3.x, n3.y, n3.z); Vector2f t3 = m.texVerticies.get((int) face.textures.z -1); GL11.glTexCoord2f(t3.x, t3.y); Vector3f v3 = m.verticies.get((int) face.vertex.z - 1); GL11.glVertex3f(v3.x, v3.y, v3.z); GL11.glEnd(); } GL11.glEndList(); The currentTexture is an int - it contains the ID of the currently used texture. So my model looks absolutely fine without textures: (sorry I cannot post hyperlinks since I am a new user) i.imgur.com/VtoK0.png But look what happens if I enable GL_TEXTURE_2D: i.imgur.com/z8Kli.png i.imgur.com/5e9nn.png i.imgur.com/FAHM9.png As you can see an entire side of the tree appears to be missing - and it's not transparent, since it's not in the colour of the background - it's rendered black. It's not a problem with the model - if I load it using Kanji's OBJ loader it works fine(but the thing is,that I need to write my own OBJ loader) i.imgur.com/YDATo.png this is my OpenGL init section: //init display try { Display.setDisplayMode(new DisplayMode(Support.SCREEN_WIDTH, Support.SCREEN_HEIGHT)); Display.create(); Display.setVSyncEnabled(true); } catch (LWJGLException e) { e.printStackTrace(); System.exit(0); } GL11.glLoadIdentity(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glClearColor(1.0f, 0.0f, 0.0f, 1.0f); GL11.glShadeModel(GL11.GL_SMOOTH); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glDepthFunc(GL11.GL_LESS); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_NORMALIZE); GL11.glMatrixMode(GL11.GL_PROJECTION); GLU.gluPerspective (90.0f,800f/600f, 1f, 500.0f); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glEnable(GL11.GL_CULL_FACE); GL11.glCullFace(GL11.GL_BACK); //enable lighting GL11.glEnable(GL11.GL_LIGHTING); ByteBuffer temp = ByteBuffer.allocateDirect(16); temp.order(ByteOrder.nativeOrder()); GL11.glMaterial(GL11.GL_FRONT, GL11.GL_DIFFUSE, (FloatBuffer)temp.asFloatBuffer().put(lightDiffuse).flip()); GL11.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS,(int)material_shinyness); GL11.glLight(GL11.GL_LIGHT2, GL11.GL_DIFFUSE, (FloatBuffer)temp.asFloatBuffer().put(lightDiffuse2).flip()); // Setup The Diffuse Light GL11.glLight(GL11.GL_LIGHT2, GL11.GL_POSITION,(FloatBuffer)temp.asFloatBuffer().put(lightPosition2).flip()); GL11.glLight(GL11.GL_LIGHT2, GL11.GL_AMBIENT,(FloatBuffer)temp.asFloatBuffer().put(lightAmbient).flip()); GL11.glLight(GL11.GL_LIGHT2, GL11.GL_SPECULAR,(FloatBuffer)temp.asFloatBuffer().put(lightDiffuse2).flip()); GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_CONSTANT_ATTENUATION, 0.1f); GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_LINEAR_ATTENUATION, 0.0f); GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_QUADRATIC_ATTENUATION, 0.0f); GL11.glEnable(GL11.GL_LIGHT2); Could somebody please help me?

    Read the article

  • Java collision detection and player movement: tips

    - by Loris
    I have read a short guide for game develompent (java, without external libraries). I'm facing with collision detection and player (and bullets) movements. Now i put the code. Most of it is taken from the guide (should i link this guide?). I'm just trying to expand and complete it. This is the class that take care of updates movements and firing mechanism (and collision detection): public class ArenaController { private Arena arena; /** selected cell for movement */ private float targetX, targetY; /** true if droid is moving */ private boolean moving = false; /** true if droid is shooting to enemy */ private boolean shooting = false; private DroidController droidController; public ArenaController(Arena arena) { this.arena = arena; this.droidController = new DroidController(arena); } public void update(float delta) { Droid droid = arena.getDroid(); //droid movements if (moving) { droidController.moveDroid(delta, targetX, targetY); //check if arrived if (droid.getX() == targetX && droid.getY() == targetY) moving = false; } //firing mechanism if(shooting) { //stop shot if there aren't bullets if(arena.getBullets().isEmpty()) { shooting = false; } for(int i = 0; i < arena.getBullets().size(); i++) { //current bullet Bullet bullet = arena.getBullets().get(i); System.out.println(bullet.getBounds()); //angle calculation double angle = Math.atan2(bullet.getEnemyY() - bullet.getY(), bullet.getEnemyX() - bullet.getX()); //increments x and y bullet.setX((float) (bullet.getX() + (Math.cos(angle) * bullet.getSpeed() * delta))); bullet.setY((float) (bullet.getY() + (Math.sin(angle) * bullet.getSpeed() * delta))); //collision with obstacles for(int j = 0; j < arena.getObstacles().size(); j++) { Obstacle obs = arena.getObstacles().get(j); if(bullet.getBounds().intersects(obs.getBounds())) { System.out.println("Collision detect!"); arena.removeBullet(bullet); } } //collisions with enemies for(int j = 0; j < arena.getEnemies().size(); j++) { Enemy ene = arena.getEnemies().get(j); if(bullet.getBounds().intersects(ene.getBounds())) { System.out.println("Collision detect!"); arena.removeBullet(bullet); } } } } } public boolean onClick(int x, int y) { //click on empty cell if(arena.getGrid()[(int)(y / Arena.TILE)][(int)(x / Arena.TILE)] == null) { //coordinates targetX = x / Arena.TILE; targetY = y / Arena.TILE; //enables movement moving = true; return true; } //click on enemy: fire if(arena.getGrid()[(int)(y / Arena.TILE)][(int)(x / Arena.TILE)] instanceof Enemy) { //coordinates float enemyX = x / Arena.TILE; float enemyY = y / Arena.TILE; //new bullet Bullet bullet = new Bullet(); //start coordinates bullet.setX(arena.getDroid().getX()); bullet.setY(arena.getDroid().getY()); //end coordinates (enemie) bullet.setEnemyX(enemyX); bullet.setEnemyY(enemyY); //adds bullet to arena arena.addBullet(bullet); //enables shooting shooting = true; return true; } return false; } As you can see for collision detection i'm trying to use Rectangle object. Droid example: import java.awt.geom.Rectangle2D; public class Droid { private float x; private float y; private float speed = 20f; private float rotation = 0f; private float damage = 2f; public static final int DIAMETER = 32; private Rectangle2D rectangle; public Droid() { rectangle = new Rectangle2D.Float(x, y, DIAMETER, DIAMETER); } public float getX() { return x; } public void setX(float x) { this.x = x; //rectangle update rectangle.setRect(x, y, DIAMETER, DIAMETER); } public float getY() { return y; } public void setY(float y) { this.y = y; //rectangle update rectangle.setRect(x, y, DIAMETER, DIAMETER); } public float getSpeed() { return speed; } public void setSpeed(float speed) { this.speed = speed; } public float getRotation() { return rotation; } public void setRotation(float rotation) { this.rotation = rotation; } public float getDamage() { return damage; } public void setDamage(float damage) { this.damage = damage; } public Rectangle2D getRectangle() { return rectangle; } } For now, if i start the application and i try to shot to an enemy, is immediately detected a collision and the bullet is removed! Can you help me with this? If the bullet hit an enemy or an obstacle in his way, it must disappear. Ps: i know that the movements of the bullets should be managed in another class. This code is temporary. update I realized what happens, but not why. With those for loops (which checks collisions) the movements of the bullets are instantaneous instead of gradual. In addition to this, if i add the collision detection to the Droid, the method intersects returns true ALWAYS while the droid is moving! public void moveDroid(float delta, float x, float y) { Droid droid = arena.getDroid(); int bearing = 1; if (droid.getX() > x) { bearing = -1; } if (droid.getX() != x) { droid.setX(droid.getX() + bearing * droid.getSpeed() * delta); //obstacles collision detection for(Obstacle obs : arena.getObstacles()) { if(obs.getRectangle().intersects(droid.getRectangle())) { System.out.println("Collision detected"); //ALWAYS HERE } } //controlla se è arrivato if ((droid.getX() < x && bearing == -1) || (droid.getX() > x && bearing == 1)) droid.setX(x); } bearing = 1; if (droid.getY() > y) { bearing = -1; } if (droid.getY() != y) { droid.setY(droid.getY() + bearing * droid.getSpeed() * delta); if ((droid.getY() < y && bearing == -1) || (droid.getY() > y && bearing == 1)) droid.setY(y); } }

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >