HaxeFlixel. Nape. DistanceJoint debugging. Drag sprite to area - debugging

I have a sprite that I can drag around on screen. I want to be able to drag this sprite into an area (box). As it stands now I can only drop the sprite into the box, but when I drag it directly inn, the program crashes.
I have debugged in FlashDevelop using the Adobe Flash debugger. When I place the sprite into the box the debugger points to this line of code in the DistanceJoint.hx file:
if(b1.space!=space||b2.space!=space)throw "Error: Constraints must have each body within the same space to which the constraint has been assigned";
I think I understand what I have to do, but I am having a hard time finding a way to make a proper exception in my Drag class.
My idea is to break the mouseJoint in the Drag class when the collideLightBox function in Playstate is used. But I do not know how to do that, or if it is the right idea. Please help.
Relevant code:
class Drag extends FlxGroup {
var mouseJoint:DistanceJoint;
public inline function registerPhysSprite(spr:FlxNapeSprite)
{
MouseEventManager.add(spr, createMouseJoint);
}
function createMouseJoint(spr:FlxSprite)
{
var body:Body = cast(spr, FlxNapeSprite).body;
mouseJoint = new DistanceJoint(FlxNapeState.space.world, body,
new Vec2(FlxG.mouse.x, FlxG.mouse.y),
body.worldPointToLocal(new Vec2(FlxG.mouse.x, FlxG.mouse.y)),
0, 0);
mouseJoint.space = FlxNapeState.space;
}
override public function update():Void
{
super.update();
if (mouseJoint != null)
{
mouseJoint.anchor1 = new Vec2(FlxG.mouse.x, FlxG.mouse.y);
if (FlxG.mouse.justReleased)
{
mouseJoint.space = null;
}
}
}
}
class PlayState extends FlxNapeState {
override public function create()
{
super.create();
bgColor = FlxColor.BLACK;
napeDebugEnabled = true;
var light = new Light(10, 10);
var box = new Box(100, 100);
var drag:Drag;
createWalls(1, 1, 1024, 768, 10, new Material(1, 1, 2, 1, 0.001));
add(light);
add(box);
drag = new Drag();
add(drag);
drag.registerPhysSprite(light);
light.body.velocity.y = 200;
FlxNapeState.space.listeners.add(new InteractionListener(
CbEvent.BEGIN,
InteractionType.COLLISION,
Light.CB_TYPE,
Box.CB_TYPE,
collideLightBox));
}
function collideLightBox(callback:InteractionCallback)
{
var light:Light = cast callback.int1.castBody.userData.sprite;
light.kill();
}
}
class Light extends FlxNapeSprite {
public static var CB_TYPE(default, null) = new CbType();
public function new(x:Float, y:Float)
{
super(x, y);
makeGraphic(10, 10, FlxColor.TRANSPARENT);
var radius = 5;
drawCircle(5, 5, radius, FlxColor.WHITE);
createCircularBody(radius);
body.cbTypes.add(CB_TYPE);
body.userData.sprite = this;
}
}
class Box extends FlxNapeSprite {
public static var CB_TYPE(default, null) = new CbType();
public function new(x:Float, y:Float)
{
super(x, y);
makeGraphic(100, 50, FlxColor.GREEN);
createRectangularBody(width, height);
body.cbTypes.add(CB_TYPE);
body.type = BodyType.STATIC;
}
}

Give Drag a function like "destroyConstraints()" and set mouseJoint.space = null inside that function. In collideLightBox, call drag.destroyConstraints().

Related

Webview OnProgressChanged and progressbar

In a Xamarin application I have a CustomWebView renderer; I'm injecting in the view and displaying a progressbar in OnProgressChanged event of the WebChromeClient with the following code.
Init:
var progressBar = new Android.Widget.ProgressBar(_context, null, Android.Resource.Attribute.ProgressBarStyleHorizontal);
Control.SetWebViewClient(new CusWebViewClient($"javascript: {JavascriptFunction}"));
Control.SetWebChromeClient(new CusWebChromeClient(progressBar));
Control.AddView(progressBar);
CusWebChromeClient:
public class CusWebChromeClient : WebChromeClient
{
Android.Widget.ProgressBar progressBar;
public CusWebChromeClient(Android.Widget.ProgressBar progressBar)
{
this.progressBar = progressBar;
}
public override void OnProgressChanged(Android.Webkit.WebView view, int newProgress)
{
if (newProgress < 100 && progressBar.Visibility == ViewStates.Gone)
{
progressBar.Visibility = ViewStates.Visible;
}
progressBar.SetProgress(newProgress, true);
if (newProgress == 100)
{
//progressBar.Visibility = ViewStates.Gone;
}
}
}
The issue is that the progress bar is displayed really small like:
I need to display it with full display width and with a more heigth.
You forgot to set the width of progress bar.
You could use the screen width to set the progress bar in custom renderer. After that, it would be okay.
var width = (int)Application.Current.MainPage.Width;
Please note, 'Application' is an ambiguous reference between 'Android.App.Application' and 'Xamarin.Forms.Application'. You could add reference like below to fix it.
using Application = Xamarin.Forms.Application;
Change:
Control.AddView(progressBar);
To:
Control.AddView(progressBar, width, 30);

Why is my customized Windows Forms panel cant handle child controls?

I want extend an System.Windows.Forms.Panel(just inherit) and using a custom ControlDesigner.
I use a very minimalistic ControlDesigner implementation, just overwrite GetHitTest.
The problem is my custom panel instance is not ready to contains child controls any longer.
I play a little bit with AssociatedComponents but without effect. Remove custom designer attribute and it works great.
can someone help me to pin point whats wrong ???
[Designer(typeof(MyPanelDesigner)), ToolboxItem(true)]
public class MyPanel : System.Windows.Forms.Panel
{
// empty except for OnPaint
}
internal class DrawPanelDesigner : ControlDesigner
{
private MyPanel ParentControl
{
get
{
return Control as MyPanel;
}
}
public override System.Collections.ICollection AssociatedComponents
{
get
{
return ParentControl.Controls;
}
}
protected override bool GetHitTest(System.Drawing.Point point)
{
// hit detection for some owner drawed items in OnPaint
point = ParentControl.PointToClient(point);
var item = ParentControl.View.GetItemFromViewPoint(point.X, point.Y, true);
return null != item;
}
You are using the wrong designer. Try inheriting from the ScrollableControlDesigner instead:
internal class DrawPanelDesigner : ScrollableControlDesigner {
public DrawPanelDesigner() {
AutoResizeHandles = true;
}
private MyPanel ParentControl {
get {
return Control as MyPanel;
}
}
protected Pen BorderPen {
get {
Color penColor = Control.BackColor.GetBrightness() < .5 ?
ControlPaint.Light(Control.BackColor) :
ControlPaint.Dark(Control.BackColor);
Pen pen = new Pen(penColor);
pen.DashStyle = DashStyle.Dash;
return pen;
}
}
protected virtual void DrawBorder(Graphics graphics) {
Panel panel = (Panel)Component;
if (panel == null || !panel.Visible) {
return;
}
Pen pen = BorderPen;
Rectangle rc = Control.ClientRectangle;
rc.Width--;
rc.Height--;
graphics.DrawRectangle(pen, rc);
pen.Dispose();
}
protected override void OnPaintAdornments(PaintEventArgs pe) {
Panel panel = (Panel)Component;
if (panel.BorderStyle == BorderStyle.None) {
DrawBorder(pe.Graphics);
}
base.OnPaintAdornments(pe);
}
}

How to add images dynamically in AS3?

Ok, i want to add a series of images, and then be able to drag and drop each one of them. I have all of my images embedded in a class Images. s0,s1,s2 are instances of image classes. Now this is what i've done
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
function init(e:Event = null):void
{
var a:Array = new Array();
var imageContainer:Sprite = new Sprite;
var imgClass:Images = new Images();
for (var i:int = 0; i < 9; i++) {
a[i].push(imgClass.(s+String(i)));
imageContainer.addChild[a[i]];
}
stage.addChild(imageContainer);
imageContainer.addEventListener(MouseEvent.MOUSE_UP, takeIt);
imageContainer.addEventListener(MouseEvent.MOUSE_DOWN, dropIt);
function takeIt(event:MouseEvent) {
event.currentTarget.startDrag();
}
function dropIt(event:MouseEvent) {
event.currentTarget.stopDrag();
}
}
}
I have rewritten your code a bit, but I have not been able to test it sorry.
The first think I notices is that your init method was inside your Main method. Then your takeIt and dropIt method were inside the init. I am not to sure if that would actually work, but I have fixed it up in the code below.
In my code I assume that the image instances you have in the Images class are instances of Bitmap. This means that inside the for loop I had to add each one to a Sprite so you have access to startDrag and stopDrag. I listen for the MOUSE_DOWN event on each image, and set the image to the selectedImage var and do startDrag. I also listen for the MOUSE_UP on the stage, and drop the currentImage.
package
{
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends Sprite
{
private var selectedImage:Sprite;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var imageContainer:Sprite = new Sprite();
var imgClass:Images = new Images();
for (var i:int = 0; i < 9; i++)
{
var imgInstance:Bitmap = imgClass['s' + i.toString()] as Bitmap;
var imgSprite:Sprite = new Sprite();
imgSprite.addChild(imgInstance); // Put image in a sprite so we can use startDrag on it.
imageContainer.addChild(imgSprite);
imgInstance.addEventListener(MouseEvent.MOUSE_DOWN, img_mouseDownHandler);
}
addChild(imageContainer);
stage.addEventListener(MouseEvent.MOUSE_UP, stage_mouseUpHandler);
}
private function dropSelectedImage():void
{
if (selectedImage)
{
selectedImage.stopDrag();
}
}
private function img_mouseDownHandler(e:MouseEvent):void
{
dropSelectedImage();
selectedImage = e.currentTarget as Sprite;
selectedImage.startDrag();
}
private function stage_mouseUpHandler(e:MouseEvent):void
{
dropSelectedImage();
}
}
}
To build your images in a loop you could also just manually build the array, then loop through the array like so:
var images:Array = [imgClass.s0, imgClass.s1, imgClass.s2, imgClass.s3, imgClass.s4, imgClass.s5, imgClass.s6, imgClass.s7, imgClass.s8];
for each (var img:Bitmap in images)
{
var imgSprite:Sprite = new Sprite();
imgSprite.addChild(img); // Put image in a sprite so we can use startDrag on it.
imageContainer.addChild(imgSprite);
imgInstance.addEventListener(MouseEvent.MOUSE_DOWN, img_mouseDownHandler);
}
Hope this help. Feel free to ask me to elaborate or explain anything else in the comments.

SlimDX Handling Window Resizing

I'm trying to handle the program window being resized, and the (I think inefficient) code I've flung together below seems to do the trick.
Is there a better way to do this, preferably one that does not create a stutter when resizing the window and which does not constantly use 12-17% of a CPU? I also suspect MessagePump.Run may somehow run before form.Resize finishes setting up the device again, and throw an error.
Thanks!
using System;
using System.Drawing;
using System.Windows.Forms;
using SlimDX;
using SlimDX.Direct3D9;
using SlimDX.Windows;
namespace SlimDX_1
{
struct Vertex
{
public Vector4 Position;
public int Color;
}
static class Program
{
private static VertexBuffer vertices;
private static Device device;
private static RenderForm form;
private static PresentParameters present;
private static VertexDeclaration vertexDecl;
private static VertexElement[] vertexElems;
private static bool wasMinimized = false;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
form = new RenderForm("Tutorial 1: Basic Window");
init();
form.Resize += (o, e) =>
{
if (form.WindowState == FormWindowState.Minimized)
{
foreach (var item in ObjectTable.Objects)
{
item.Dispose();
}
wasMinimized = true;
}
else
{
foreach (var item in ObjectTable.Objects)
{
item.Dispose();
}
init();
device.SetRenderState(RenderState.FillMode, FillMode.Wireframe);
device.SetRenderState(RenderState.CullMode, Cull.None);
present.BackBufferHeight = form.ClientSize.Height;
present.BackBufferWidth = form.ClientSize.Width;
device.Reset(present);
}
};
MessagePump.Run(form, () =>
{
if (form.WindowState == FormWindowState.Minimized)
{
return;
}
device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
device.BeginScene();
device.SetStreamSource(0, vertices, 0, 20); // 20 is the size of each vertex
device.VertexDeclaration = vertexDecl;
device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
device.EndScene();
device.Present();
});
foreach (var item in ObjectTable.Objects)
{
item.Dispose();
}
}
private static void init()
{
present = new PresentParameters();
//present.EnableAutoDepthStencil = false;
//present.BackBufferCount = 1;
//present.SwapEffect = SwapEffect.Discard;
present.Windowed = true;
present.BackBufferHeight = form.ClientSize.Height;
present.BackBufferWidth = form.ClientSize.Width;
//present.BackBufferFormat = Format.Unknown;
device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, present);
vertices = new VertexBuffer(device, 3 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
vertices.Lock(0, 0, LockFlags.None).WriteRange(new Vertex[]
{
new Vertex() { Color = Color.Red.ToArgb(), Position = new Vector4(400.0f, 100.0f, 0.5f, 1.0f) },
new Vertex() { Color = Color.Blue.ToArgb(), Position = new Vector4(650.0f, 500.0f, 0.5f, 1.0f) },
new Vertex() { Color = Color.Green.ToArgb(), Position = new Vector4(150.0f, 500.0f, 0.5f, 1.0f) }
});
vertices.Unlock();
// specifies the layout of the vertexes
vertexElems = new VertexElement[]
{
new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0),
new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
VertexElement.VertexDeclarationEnd
};
vertexDecl = new VertexDeclaration(device, vertexElems);
}
}
}
You're going way above and beyond what you need to do when the window is resized. You're releasing every single DirectX object you've created, including the graphics device, and then recreating everything. This is going to take a comparatively long time, which is why you're seeing performance issues.
In fact, none of your objects need to be released. Simply call the Reset() function on the device to recreate the backbuffer to match the new window size. Check out some of the native Direct3D9 tutorials on window resizing to see how in general how the process works.

Transition of images in Windows Forms Picture box

I'm new to Windows Forms, in my project, i need to change the image in the picture box at runtime. I'm able to do that with the help of a timer. The picture just gets changed. Is it possible to do some transitions when image changes, for example fade in, fade out, blur etc.. If possible could some one please let me know how to do it. I searched in net but in vain.Thanks in advance.
Varun
Simply take new code file and paste below code in it
an original answer for the similar question, answer taken from another question
Answer
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
public class BlendPanel : Panel
{
private Image mImg1;
private Image mImg2;
private float mBlend;
public BlendPanel()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true);
}
public Image Image1
{
get { return mImg1; }
set { mImg1 = value; Invalidate(); }
}
public Image Image2
{
get { return mImg2; }
set { mImg2 = value; Invalidate(); }
}
public float Blend
{
get { return mBlend; }
set { mBlend = value; Invalidate(); }
}
protected override void OnPaint(PaintEventArgs e)
{
if (mImg1 == null || mImg2 == null)
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), new Rectangle(0, 0, this.Width, this.Height));
else
{
Rectangle rc = new Rectangle(0, 0, this.Width, this.Height);
ColorMatrix cm = new ColorMatrix();
ImageAttributes ia = new ImageAttributes();
cm.Matrix33 = mBlend;
ia.SetColorMatrix(cm);
e.Graphics.DrawImage(mImg2, rc, 0, 0, mImg2.Width, mImg2.Height, GraphicsUnit.Pixel, ia);
cm.Matrix33 = 1F - mBlend;
ia.SetColorMatrix(cm);
e.Graphics.DrawImage(mImg1, rc, 0, 0, mImg1.Width, mImg1.Height, GraphicsUnit.Pixel, ia);
}
base.OnPaint(e);
}
}
Build your project. You can now drop a BlendPanel from the top of the toolbox onto your form. Here's a sample program that uses it:
private float mBlend;
private int mDir = 1;
public int count = 0;
public Bitmap[] pictures;
public void myPhoto()
{
pictures = new Bitmap[9];
pictures[0] = new Bitmap(#"Library Images\cf3.jpg");
pictures[1] = new Bitmap(#"Library Images\cf4.jpg");
pictures[2] = new Bitmap(#"Library Images\l1.JPG");
pictures[3] = new Bitmap(#"Library Images\l2.JPG");
pictures[4] = new Bitmap(#"Library Images\l3.JPG");
pictures[5] = new Bitmap(#"Library Images\l4.JPG");
pictures[6] = new Bitmap(#"Library Images\l5.JPG");
pictures[7] = new Bitmap(#"Library Images\l6.JPG");
pictures[8] = new Bitmap(#"Library Images\l7.JPG");
timer1.Interval = 50; //time of transition
timer1.Tick += BlendTick;
try
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[++count];
}
catch
{
}
timer1.Enabled = true;
}
private void BlendTick(object sender, EventArgs e)
{
mBlend += mDir * 0.02F;
if (mBlend > 1)
{
mBlend = 0.0F;
if ((count + 1) < pictures.Length)
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[++count];
}
else
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[0];
count = 0;
}
}
blendPanel1.Blend = mBlend;
}
You'll need to modify the new Bitmap(#"yourimagePath"); calls. Build and run. You should see the displayed image smoothly morph from your first image to your second image without any flickering.
I hope it helps for other...
There is no built-in support for such effects, but you can implement them. I'd suggest to write a custom control that renders the image and have a method for fade-swap, fade itself can be reached with alpha-blending drawing with .NET Graphics class.
However, Graphics class isn't very fast, I don't recommend to use this technique for big images. If you need some fancy UI with hw-accelerated effects, take a look at WPF.
Blend effects are easy to get going by using the ColorMatrix class. There's a good example available in my answer in this thread.
A simple way to get a blur is to resize the image, making it smaller, then redraw it back, making it larger. The Graphics.InterpolationMode property affects the type of blur you'll get.
Those are quicky do-it-yourself solutions. Any decent graphics library has these kind of operations built-in. You probably want something free, check out ImageMagick.NET
To put it simply, not without external (3rd-party) libraries.

Resources