storyBoard animation rotation issue - windows-phone-7

i am rotating a button on click at 180 degree, and its working fine
AnimationServices.RotationAnimation((FrameworkElement)sender, 180, 1, "Y"); // working
but when i do the same thing by rotating it two times with 90 degree angle than its not working
AnimationServices.RotationAnimation((FrameworkElement)sender, 90, 1, "Y");
AnimationServices.RotationAnimation((FrameworkElement)sender, 90, 1, "Y"); // not working
its only rotating at one 90 degree angle
does anyone have any idea about this strange issue ?
UpDate
internal static void RotationAnimation(FrameworkElement sender, int Angle, int DurationInMSec, String Axis)
{
var storyboard = new Storyboard();
var easingDoubleKeyFrame1 = new EasingDoubleKeyFrame
{
KeyTime = TimeSpan.FromMilliseconds(0),
Value = 0
};
var easingDoubleKeyFrame2 = new EasingDoubleKeyFrame
{
KeyTime = TimeSpan.FromMilliseconds(DurationInMSec),
Value = Angle
};
var doubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames();
doubleAnimationUsingKeyFrames.KeyFrames.Add(easingDoubleKeyFrame1);
doubleAnimationUsingKeyFrames.KeyFrames.Add(easingDoubleKeyFrame2);
var rotateTransform = new PlaneProjection();
var button = (FrameworkElement)sender;
button.Projection = rotateTransform;
Storyboard.SetTarget(doubleAnimationUsingKeyFrames, rotateTransform);
Storyboard.SetTargetProperty(doubleAnimationUsingKeyFrames, new PropertyPath("Rotation" + Axis));
storyboard.Children.Add(doubleAnimationUsingKeyFrames);
storyboard.Begin();
}

It's hard to tell what's going on if you don't provide the code of your RotationAnimation method. Still, it's very likely that this method is trying to execute the same animation two times simultaneously. So you have two animations trying to rotate the same element from 0 to 90 degrees. Which makes... 90 degrees. Either change the rotation angle of the currently executing animation, or wait for the current one to finish executing before launching a new one. Asking two different animations to animate simultaneously the same property cannot possibly provide consistent results.
Edit: After seeing your code, that's indeed the problem. You're creating two animations, that will both rotate from 0 to 90 degrees. You need to chain two animations, and add an "origin" parameter to your method so the second animation will start rotating from 90° (and not from 0). To chain the animation, you can modify your method to return the created animation, then subscribe to the Completed event.
Something like that:
internal static Storyboard RotationAnimation(FrameworkElement sender, int origin, int Angle, int DurationInMSec, String Axis)
{
var storyboard = new Storyboard();
var easingDoubleKeyFrame1 = new EasingDoubleKeyFrame
{
KeyTime = TimeSpan.FromMilliseconds(0),
Value = origin
};
var easingDoubleKeyFrame2 = new EasingDoubleKeyFrame
{
KeyTime = TimeSpan.FromMilliseconds(DurationInMSec),
Value = Angle + origin
};
var doubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames();
doubleAnimationUsingKeyFrames.KeyFrames.Add(easingDoubleKeyFrame1);
doubleAnimationUsingKeyFrames.KeyFrames.Add(easingDoubleKeyFrame2);
var rotateTransform = new PlaneProjection();
var button = (FrameworkElement)sender;
button.Projection = rotateTransform;
Storyboard.SetTarget(doubleAnimationUsingKeyFrames, rotateTransform);
Storyboard.SetTargetProperty(doubleAnimationUsingKeyFrames, new PropertyPath("Rotation" + Axis));
storyboard.Children.Add(doubleAnimationUsingKeyFrames);
storyboard.Begin();
return storyboard;
}
Then you can call it like that:
var storyboard = RotateAnimation((FrameworkElement)sender, 0, 90, 1, "Y");
storyboard.Completed += (s, e) => RotateAnimation((FrameworkElement)sender, 90, 90, 1, "Y");

Related

Three.js: Rotate object with lookAt() while located at the current lookAt() position

I'm trying to implement a simple turn-around-and-move feature with Three.js. On mouse click, the object is supposed to first turn around and then move to the clicked location.
Codepen
The rotation is achieved with raycasting and lookAt(). It works by itself and it always works on the first click. If you remove the translation, it works continuously. The issue occurs when rotation and translation are implemented together. If you click a second time, after the object has moved to the previous clicked location, it doesn't rotate as expected. Depending on the mouse location it can flip to the other side without rotating at all.
Clarification: When you click the first time, notice how the object slowly and steadily turns around to face that direction? But the second time, after the object has moved, the rotation is quicker and/or flimsier or it simply flips over and there is no rotation at all. It depends on where you click in relation to the object.
I believe the issue stems from trying to implement lookAt while being located at the current lookAt location? If I stop the translation half way, the next rotation will work better. But of course I need it to go all the way.
I'm somewhat lost on how to proceed with this issue. Any help would be appreciated.
/*** Setup scene ***/
let width = 800
let height = 600
let scene
let renderer
let worldAxis
let box
let angle
let boxAxes
scene = new THREE.Scene()
worldAxis = new THREE.AxesHelper(200);
scene.add(worldAxis);
// Setup renderer
renderer = new THREE.WebGLRenderer({alpha: true, antialias: true})
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(width, height)
document.body.appendChild(renderer.domElement)
// Setup camera
const camera = new THREE.OrthographicCamera(
width / - 2, // left
width / 2, // right
height / 2, // top
height / - 2, // bottom
0, // near
1000 ); // far
camera.position.set(0, 0, 500)
camera.updateProjectionMatrix()
// Setup box
let geometry = new THREE.BoxGeometry( 15, 15, 15 );
let material = new THREE.MeshBasicMaterial( { color: "grey" } );
box = new THREE.Mesh( geometry, material );
box.position.set(100, 150, 0)
box.lookAt(getPointOfIntersection(new THREE.Vector2(0, 0)))
addAngle()
boxAxes = new THREE.AxesHelper(50);
box.add(boxAxes)
scene.add(box)
renderer.render(scene, camera);
/*** Setup animation ***/
let animate = false
let currentlyObservedPoint = new THREE.Vector2();
let rotationIncrement = {}
let translationIncrement = {}
let frameCount = 0
document.addEventListener('click', (event) => {
let mousePosForRotate = getMousePos(event.clientX, event.clientY)
rotationIncrement.x = (mousePosForRotate.x - currentlyObservedPoint.x)/100
rotationIncrement.y = (mousePosForRotate.y - currentlyObservedPoint.y)/100
let mousePosForTranslate = getMousePosForTranslate(event)
translationIncrement.x = (mousePosForTranslate.x - box.position.x)/100
translationIncrement.y = (mousePosForTranslate.y - box.position.y)/100
animate = true
})
function animationLoop() {
if (animate === true) {
if (frameCount < 100) {
rotate()
} else if (frameCount < 200) {
translate()
} else {
animate = false
frameCount = 0
}
frameCount++
renderer.render(scene, camera)
}
requestAnimationFrame(animationLoop)
}
function rotate() {
currentlyObservedPoint.x += rotationIncrement.x
currentlyObservedPoint.y += rotationIncrement.y
let pointOfIntersection = getPointOfIntersection(currentlyObservedPoint)
box.lookAt(pointOfIntersection)
addAngle()
}
function translate() {
box.position.x += translationIncrement.x
box.position.y += translationIncrement.y
}
function getMousePos(x, y) {
let mousePos = new THREE.Vector3(
(x / width) * 2 - 1,
- (y / height) * 2 + 1,
0)
return mousePos
}
function getMousePosForTranslate(event) {
let rect = event.target.getBoundingClientRect();
let mousePos = { x: event.clientX - rect.top, y: event.clientY - rect.left }
let vec = getMousePos(mousePos.x, mousePos.y)
vec.unproject(camera);
vec.sub(camera.position).normalize();
let distance = - camera.position.z / vec.z;
let pos = new THREE.Vector3(0, 0, 0);
pos.copy(camera.position).add(vec.multiplyScalar(distance));
return pos
}
function getPointOfIntersection(mousePos) {
let plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
let pointOfIntersection = new THREE.Vector3()
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mousePos, camera)
raycaster.ray.intersectPlane(plane, pointOfIntersection)
return pointOfIntersection
}
function addAngle() {
let angle = box.rotation.x - 32
box.rotation.x = angle
}
animationLoop()
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/105/three.min.js'></script>

Skia / SkiaSharp - Rotating shapes around their own vertical axis

I generate the scene above using the OnDraw method below:
protected override void OnDraw(SKCanvas canvas, int width, int height)
{
int i = 0;
int step = 0;
List<SKRect> rects = new List<SKRect>();
// get the 2D equivalent of the 3D matrix
var rotationMatrix = rotationView.Matrix;
// get the properties of the rectangle
var length = Math.Min(width / 6, height / 6);
canvas.Clear(EffectMedia.Colors.XamarinLightBlue);
foreach (var n in numbers)
{
var rect = new SKRect(0 + step, 0, 100 + step, 100);
rects.Add(rect);
step += 120;
}
//var sideHoriz = rotationMatrix.MapPoint(new SKPoint(0, 1)).Y > 0;
var sideVert = rotationMatrix.MapPoint(new SKPoint(1, 0)).X > 0;
var paint = new SKPaint
{
Color = sideVert ? EffectMedia.Colors.XamarinPurple : EffectMedia.Colors.XamarinGreen,
Style = SKPaintStyle.Fill,
IsAntialias = true
};
// first do 2D translation to the center of the screen
canvas.Translate((width - (120 * numbers.Count)) / 2, height / 2);
// The following line is disabled because it makes the whole canvas rotate!
// canvas.Concat(ref rotationMatrix);
foreach (var n in numbers)
{
canvas.RotateDegrees((float)-3);
canvas.DrawRoundRect(rects[i], 30, 30, paint);
var shadow = SKShader.CreateLinearGradient(
new SKPoint(0, 0), new SKPoint(0, length * 2),
new[] { paint.Color.WithAlpha(127), paint.Color.WithAlpha(0) },
null,
SKShaderTileMode.Clamp);
var paintShadow = new SKPaint
{
Shader = shadow,
Style = SKPaintStyle.Fill,
IsAntialias = true,
BlendMode = SKBlendMode.SoftLight
};
foreach (var r in rects)
{
r.Offset(0, 105);
canvas.DrawRoundRect(r, 30, 30, paintShadow);
}
i++;
}
}
The idea is to make all those rounded boxes rotate (vertically) around their own axis.
I tried using SKPath + Transform, saving&restoring the rotationMatrix and/or the canvas but I can't find a way to have 6 rotating boxes ( canvas.Concat(ref rotationMatrix); makes the whole canvas rotate [*]).
Do you have any hint on how that can be achieved?
Note [*]: there's a call to rotationView.RotateYDegrees(5) every X milliseconds to update the rotationMatrix used by OnDraw.
This is what I'd like to achieve, any hints / directions would be really appreciated... :-)
The following piece of code rotates those shapes around their Z-axis:
canvas.Save();
canvas.RotateDegrees(degrees, rects[i].MidX, rects[i].MidY);
canvas.DrawRoundRect(rects[i], 30, 30, paint);
canvas.Restore();
Thanks

How to specify a rectangle from the CGPoint Start and End?

I have a rectangle bounds (10, 20, 100, 200) and the CGPoints are StartPoint (0.5, 0.5) and EndPoints as (1, 1). From these points how needs to calculate the segments bounds ? I need to apply this bounds for CGGradient for start point and end points.
Eg Code :
GradientColor gradientColor1 = new GradientColor(){StartPoint = new CGPoint(0.5, 0), EndPoint= new CGPoint(0.5, 1)};
GradientStop stop1 = new GradientStop() { Color = UIColor.Red, Offset = 0.1f };
GradientStop stop2 = new GradientStop() { Color = UIColor.Blue, Offset = 0.9f };
can you please help me out of this?
Here an an example that will create a left to right linear gradient within the current CGContext.
using (var context = UIGraphics.GetCurrentContext ()) {
context.SaveState();
var startPoint = new CGPoint(rect.Left, 0);
var endPoint = new CGPoint(rect.Right, 0);
var components = new CGColor[] { UIColor.Red.CGColor, UIColor.Blue.CGColor };
using (var rgb = CGColorSpace.CreateDeviceRGB()) {
var gradient = new CGGradient(rgb, components);
context.DrawLinearGradient(gradient, startPoint, endPoint, CGGradientDrawingOptions.DrawsBeforeStartLocation);
};
context.RestoreState();
}
Changing the start and end points you can have the gradient paint right to left, up/down, diagonal, etc..

The sprite animation in my simple easeljs script is not showing up

I am trying my hand at easeljs and animating a spritesheet. This is the first time I am working with sprites and as such am not knowledgeable about them.
My simple easeljs code to show this specific animation is;
var stage;
function init() {
// create a new stage and point it at our canvas:
stage = new createjs.Stage(document.getElementById("demoCanvas"));
var data = {
images: ["http://i.imgur.com/g5WtL7v.png"],
frames: {width:256, height:256},
animations: {
run:[0,4]
}
};
var spriteSheet = new createjs.SpriteSheet(data);
var animation = new createjs.BitmapAnimation(spriteSheet);
animation.gotoAndPlay("run");
}
But the sprite doesn't shows up on the canvas at all. WHat am I doing wrong?
Additional question;
defining frames in easeljs can be done by
frames: [ // x, y, width, height, imageIndex, regX, regY
While I do understand width and height, what are x, y, imageIndex and regX, regY. The documentaion explains how I can use these parameters but for someone who is working with sprites for the 1st time in my life, I just dont know what these terms mean.
EDIT: I have also tried changing the code as such;
var stage;
function init() {
// create a new stage and point it at our canvas:
stage = new createjs.Stage("demoCanvas");
var data = {
images: ["http://i.imgur.com/g5WtL7v.png"],
frames: {width:256, height:256, count:8},
animations: {
run:[0,4, true]
}
};
var ss = new createjs.SpriteSheet(data);
var animation = new createjs.BitmapAnimation(ss);
animation.x = 100;
animation.y = 100;
stage.addChild(animation);
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", stage);
}
But I am still seeing a blank canvas...
You are missing a frame-count in the frames-object:
frames: {width:...,height:...,count:4} // or whatever number of frames your sprite holds
And just in case: The width and height is the width and height of 1 frame, not the entire image.
See more information and examples here: http://www.createjs.com/Docs/EaselJS/classes/SpriteSheet.html
ok i got things to work by combining both the codes that I have listed above;
var stage;
function init() {
// create a new stage and point it at our canvas:
stage = new createjs.Stage("demoCanvas");
var data = {
images: ["http://i.imgur.com/g5WtL7v.png"],
frames: {width:256, height:256, count:8},
animations: {
run:[0,4, true]
}
};
var ss = new createjs.SpriteSheet(data);
var animation = new createjs.BitmapAnimation(ss);
animation.x = 100;
animation.y = 100;
stage.addChild(animation);
animation.gotoAndPlay("run");
createjs.Ticker.setFPS(10);
createjs.Ticker.addEventListener("tick", stage);
}
Now I have some questions;
If I need animation.gotoAndPlay("run"); to animate the sprite how come the code at https://github.com/CreateJS/EaselJS/blob/master/examples/SpriteSheet_simple.html doesn't needs it?
whats the difference between new createjs.Sprite(ss, "run"); and new createjs.BitmapAnimation(spriteSheet); . I am unable to find any documentation of the former.

AS3 stagesized Bitmap and update regions

I have a project where i'm drawing to a stageSized bitmap by using BitmapData.draw
using the 'show update regions' feature of the debug player, i can see that the player always updates the whole stage although i changed only a small part of the bitmapdata.
Can I somehow make the player only update that part of the screen where there were changes made to the bitmap data?
Would it be possible to use copyPixels instead? It only allows copying from another BitmapData, but most of the time that should be fine (you could always cache animations to bitmapdata once, and then use the cached data instead of the Draw-method). Flash player should be able to redraw only the altered parts when you use copyPixels.
However, the real question; is this really an issue? Don't optimize these things unless you actually need to :)
If you're only redrawing part of the bitmap, then only that part should get updated by Flash Player.
You can see it in action here:
public class Test extends Sprite
{
public function Test()
{
stage.align = "topLeft";
stage.scaleMode = "noScale";
var bitmap:Bitmap = new Bitmap();
addChild(bitmap);
var bd:BitmapData = new BitmapData(400, 400);
bitmap.bitmapData = bd;
// One-second timer.
var timer:Timer = new Timer(1000);
timer.start();
timer.addEventListener("timer", timerHandler);
}
private function timerHandler(event:Event):void
{
var bitmap:Bitmap = Bitmap(getChildAt(0));
var bd:BitmapData = bitmap.bitmapData;
// Draw 100x100 square in random location, with random color.
var xPos:Number = Math.random() * 300;
var yPos:Number = Math.random() * 300;
var matrix:Matrix = new Matrix(1, 0, 0, 1, xPos, yPos);
var color:uint = Math.round(Math.random() * 0xFFFFFF) | 0xFF000000;
var colorTransform:ColorTransform = new ColorTransform();
colorTransform.color = color;
var shape:Shape = new Shape();
var g:Graphics = shape.graphics;
g.beginFill(0xFFFFFF);
g.drawRect(0, 0, 100, 100);
g.endFill();
bd.draw(shape, matrix, colorTransform);
}
}
Try this with "Show Redraw Regions" in the standalone Flash Player, and you'll see it updates only the newly drawn part on each tick.

Resources