Play an animation when touch moved is certain distance from touch began - animation

i am new to unityscript and unity and i am trying to make an animation trigger when the touch moved position is +100 to the right of touch began, so i have also tried +500 and +1000 and it seems that the animation is playing when the touch is past 100,500,or 1000 on the screen, not the touch.began position + (the amount), any help is appreciated, thank you for your time as i am new to unityscript
#pragma strict
var distance : float = 10;
var joystick : GameObject;
private var first : boolean = false;
function Start () {
}
function Update () {
transform.eulerAngles = Vector3(0,Camera.main.transform.eulerAngles.y + 180,0);
var v3Pos : Vector3;
if (Input.touchCount > 0 &&
Input.GetTouch(0).phase == TouchPhase.Began) {
// Get movement of the finger since last frame
var touchDeltaPosition:Vector2 = Input.GetTouch(0).position;
if(!first){
var touchdet : Vector2 = touchDeltaPosition;
first = true;
}
// Move object across XY plane
v3Pos = Vector3(touchDeltaPosition.x, touchDeltaPosition.y, distance);
transform.position = Camera.main.ScreenToWorldPoint(v3Pos);
}
if (Input.touchCount > 0 &&
Input.GetTouch(0).phase == TouchPhase.Moved) {
// Get movement of the finger since last frame
var touchAlphaPosition:Vector2 = Input.GetTouch(0).position;
// Move object across XY plane
v3Pos = Vector3(touchAlphaPosition.x, touchAlphaPosition.y, distance);
transform.position = Camera.main.ScreenToWorldPoint(v3Pos);
}
if (Input.touchCount > 0 &&
(Input.GetTouch(0).phase == TouchPhase.Ended || Input.GetTouch(0).phase == TouchPhase.Canceled )) {
// Get movement of the finger since last frame
var touchBetaPosition:Vector2 = Input.GetTouch(0).position;
first = false;
// Move object across XY plane
v3Pos = Vector3(touchBetaPosition.x, 600, distance);
transform.position = Camera.main.ScreenToWorldPoint(v3Pos);
}
if(first)
{
if(touchAlphaPosition.x > touchdet.x + 100)
{
animation.Play("Right");
}
}
}

The variable touchDet is declared and initialized in the function Update, so the value is not persisted between function calls. touchDet in all but the iteration where TouchPhase.Began event fires will always be equal to Vector2.zero.

Related

How do I scale translate x,y values?

I am working on a 2d grid with scale touch functionality. I've managed to set the translate boundaries so that the screen viewport doesn't go beyond the grid boundaries. I'm now struggling with the algorithm for determining the new translate values when scaling on both two finger touch and mouse wheel events.
touchStarted sets the vector angle between the two initial touches. lastTouchAngle is for comparison in touchMoved.
function touchStarted() {
if(touches.length == 2) {
let touchA = createVector(touches[0].x, touches[0].y);
let touchB = createVector(touches[1].x, touches[1].y);
lastTouchAngle = touchA.angleBetween(touchB);
}
return false;
}
touchMoved makes the current touches vectors, compares the angle, and then scales accordingly.
t_MinX and t_MinY set the lowest possible translate value for the constrains, but determining what the new translate value should be is where I'm lost. I know it's going to require the current scale, the center point between the two touches, and the width and height of the Canvas.
function touchMoved() {
if(touches.length == 1) {
panTranslate(translateX, translateY, mouseX, mouseY, pmouseX, pmouseY);
} else if (touches.length == 2) {
let touchA = createVector(touches[0].x, touches[0].y);
let touchB = createVector(touches[1].x, touches[1].y);
scl = (abs(lastTouchAngle) < abs(touchA.angleBetween(touchB)) ? (scl+sclStep < sclMax ? scl+sclStep : sclMax) : (scl-sclStep > sclMin ? scl-sclStep : sclMin));
let t_MinX = (screenH/sclMin) * (sclMin-scl);
let t_MinY = (screenW/sclMin) * (sclMin-scl);
let tX = translateX;
let tY = translateY;
if(abs(lastTouchAngle) > abs(touchA.angleBetween(touchB))) {
console.log("Scale out");
translateX = constrain(tX+mX, t_MinX, 0);
translateY = constrain(tY+mY, t_MinY, 0);
} else {
console.log("Scale in");
if(scl != sclMax) {
translateX = constrain(tX-mX, t_MinX, 0);
translateY = constrain(tY-mY, t_MinY, 0);
}
}
// Set current touch angle to lastTouchAngle
lastTouchAngle = touchA.angleBetween(touchB);
}
return false;
}
Here is the bit getting me confused:
translateX = constrain(tX+mX, t_MinX, 0);
translateY = constrain(tY+mY, t_MinY, 0);
Full code: https://editor.p5js.org/OMTI/sketches/9ux6Rq6n5
https://stackoverflow.com/questions/5713174
I found the answer at the above link and was able to get this working from the answer there.

Bug found in scrolling smooth code found in someone else post but don't know how to fix

I search on my friend Google for some code to do smooth scroll and found this : Smooth vertical scrolling on mouse wheel in vanilla javascript?
It works well but if i scroll once and then try to use my mouse to manually move the scrollbar, it's broken...
SmoothScroll(document, 120, 12);
function SmoothScroll(target, speed, smooth) {
if (target === document)
target = (document.scrollingElement ||
document.documentElement ||
document.body.parentNode ||
document.body) // cross browser support for document scrolling
var moving = false
var pos = target.scrollTop
var frame = target === document.body &&
document.documentElement ?
document.documentElement :
target // safari is the new IE
target.addEventListener('scroll', scrolled, {
passive: false
})
target.addEventListener('mousewheel', scrolled, {
passive: false
})
target.addEventListener('DOMMouseScroll', scrolled, {
passive: false
})
function scrolled(e) {
e.preventDefault(); // disable default scrolling
var delta = normalizeWheelDelta(e)
pos += -delta * speed
pos = Math.max(0, Math.min(pos, target.scrollHeight - frame.clientHeight)) // limit scrolling
if (!moving) update()
}
function normalizeWheelDelta(e) {
if (e.detail) {
if (e.wheelDelta)
return e.wheelDelta / e.detail / 40 * (e.detail > 0 ? 1 : -1) // Opera
else
return -e.detail / 3 // Firefox
} else
return e.wheelDelta / 120 // IE,Safari,Chrome
}
function update() {
moving = true
var delta = (pos - target.scrollTop) / smooth
target.scrollTop += delta
if (Math.abs(delta) > 0.5)
requestFrame(update)
else
moving = false
}
var requestFrame = function () { // requestAnimationFrame cross browser
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (func) {
window.setTimeout(func, 1000 / 50);
}
);
}()
}
So... i want it to work properly when i already scroll once but try to use the mouse to move the scrollbar instead of mousewheel.
Thanks for helping!
Looks like you could fix it by re-adjusting the pos variable to the scrollTop before your scrolling calculations.
Additionally theres a bug where your scroll could get stuck in an infinite render loop causing you to never stop animating. This was due to the delta being .5 < delta < 1 making the request frame get called forever. You cant actually move the scrollTop anything less than 1 so I adjusted the conditions for another render loop and rounded the delta
function scrolled(e) {
// if currently not animating make sure our pos is up to date with the current scroll postion
if(!moving) {
pos = target.scrollTop;
}
e.preventDefault(); // disable default scrolling
var delta = normalizeWheelDelta(e)
pos += -delta * speed
pos = Math.max(0, Math.min(pos, target.scrollHeight - frame.clientHeight)) // limit scrolling
if (!moving) update()
}
function update() {
moving = true;
// scrollTop is an integer and moving it by anything less than a whole number wont do anything
// to prevent a noop and an infinite loop we need to round it
var delta = absRound((pos - target.scrollTop) / smooth)
target.scrollTop += delta
if (Math.abs(delta) >= 1) {
requestFrame(update)
} else {
moving = false
}
}
function absRound(num) {
if(num < 0) {
return -1*Math.round(-1*num);
} else {
return Math.round(num);
}
}
That way when manually adjusting the scroll position if the wheel is used it doesnt jump to the position it was once at, but instead adjust itself to the current scroll position.

Triggering a Lottie animation onScroll

im currently building a website using fullpage js and lottie animations. Now im trying to trigger an animation when the user scrolls to the section with the animation. Here is what i tried:
(please note that im very new to js)
$(document).ready(function($) {'use strict';
$('#fullpage').fullpage({
sectionsColor: ['white', '#004E8A', 'white','#004E8A', 'white', '#004E8A',
'white','#004E8A', 'white'],
anchors:['startseite','pers_vermittler','team','konzept','rechner','mod_portfolio','sicherheit','absatz'],
onLeave: function(index, nextIndex, direction) {
if( index == 3 && direction == 'down' ) {
lottie.play('k2an');
}
(at the end of the body section ->)
<script>
var params = {
container: document.getElementById('k2an'),
renderer: 'svg',
loop: true,
autoplay: false,
path: 'k2an.json',
};
anim = lottie.loadAnimation(params);
You should be using fullPage.js callbacks to fire your JS animations.
See the example:
$('#fullpage').fullpage({
anchors: ['firstPage', 'secondPage', 'thirdPage', 'fourthPage', 'lastPage'],
afterLoad: function(anchorLink, index){
var loadedSection = $(this);
//using index
if(index == 3){
alert("Section 3 ended loading");
}
//using anchorLink
if(anchorLink == 'secondSlide'){
alert("Section 2 ended loading");
}
}
});
Feel free to also check my video tutorial on how to create animations using fullPage.js state classes.
Right now im using this approach on a couple production sites. It plays the animation as the user scrolls.
I basically check how much of the animation objects box is visible in the viewport, calculate the total length of the animation (in frames) and then project the percentage to a frame where i gotoAndStop().
var anim = <YOUR LOTTIE ANIMATION OBJECT>
// play around with these
var speed = 1; // speed of animation
var scrollOffset = 0; // start animation sooner / later
function scrollHandler() {
if (!anim.isLoaded) return;
p = percentageSeen(e) / 100 - (scrollOffset || 0);
if (p <= 0 || p >= 1) return
var length = anim.totalFrames / anim.frameModifier;
var pos = length * p * (speed || 1);
anim.goToAndStop(pos);
}
$(window).on('scroll', scrollHandler);
/**
* returns percentage of scrolling element through viewport
* 0% until element-middle is at bottom of viewport
* 100% if element-middle is at top of viewport
*
* #param id
* #returns {number}
*/
function percentageSeen(idOrElement) {
var $element;
if (typeof idOrElement === 'object') {
$element = idOrElement;
} else {
$element = $('#' + id);
if (!$element[0]) return 0;
}
var $win = $(window), viewportHeight = $(window).height(),
scrollTop = $win.scrollTop(),
elementOffsetTop = $element.offset().top,
elementHeight = $element.height();
if (elementOffsetTop > (scrollTop + viewportHeight)) {
return 0;
} else if ((elementOffsetTop + elementHeight) < scrollTop) {
return 100;
} else {
var distance = (scrollTop + viewportHeight) - elementOffsetTop - (elementHeight / 2);
if (distance < 0) return 0;
var percentage = distance / (viewportHeight / 100);
if (percentage > 100) return 100;
return percentage;
}
}
If you want to only start the animation and let it run (independently of further user-scrolling-behaviour), just use the jquery inview plugin, disable autoplay on your animation and trigger the play() once like this:
$(".animation-container").one("inview", function() {
anim.play()
});

Unity3d HTC Vive Radial Menu - Weird Glitching

So i wrote this radial Menu controlled by the trackpad on the left-hand wand. It determine which button to magnify by my fingers position on trackpad.
The Weird movement can be seen here.
Here i attacked my code related to this problem, the code for left wand.
SteamVR_TrackedObject obj; //The wand
public GameObject buttonHolder; //All the buttons will be children of this object
public bool buttonEnabled;
void Awake() {
obj = GetComponent<SteamVR_TrackedObject>(); //this will be left hand controller
}
void Update() {
var device = SteamVR_Controller.Input((int)obj.index);
//if touchpad touched
if (device.GetTouch(SteamVR_Controller.ButtonMask.Touchpad))
{
if (buttonEnabled) //if radial menu is open
{
//touchPadAngle: Get the angle between touch coord and X-axis
Vector2 touchedCoord = device.GetAxis(EVRButtonId.k_EButton_Axis0); //what is this line each variable
float touchPadAngle = VectorAngle(new Vector2(1, 0), touchedCoord); //(1, 0) is X-axis
// ------------------- Find closest button ------------------------
//Description: The process will be done by calculating the angle between button_Vector2 and X-axis (button_V2_to_10)
// And then find the button with the closest angler difference with (touchPadAngle).
float minAngle = float.PositiveInfinity;
Transform minButton = transform; //Temperatry assign wand tranform to it.
float pad_N_button_Angle = 0.0f; //Angle between touchPadAngle and buttonAngle.
Vector2 button_V2_to_10;
float button_Angle;
foreach (Transform bt in buttonHolder.transform)
{
button_V2_to_10 = new Vector2(transform.position.x, transform.position.z) - new Vector2(bt.position.x, bt.position.z);
button_Angle = VectorAngle(new Vector2(1, 0), button_V2_to_10);
pad_N_button_Angle = Mathf.Abs(button_Angle - touchPadAngle);
//Both buttonAngle and touchPadAngle range from -180 to 180, avoid Abs(170 - (-170)) = 340
pad_N_button_Angle = (pad_N_button_Angle > 180) ? Mathf.Abs(pad_N_button_Angle - 360) : pad_N_button_Angle;
if (pad_N_button_Angle < minAngle)
{
minButton = bt;
minAngle = pad_N_button_Angle;
}
}
//Magnify the closest button
foreach (Transform bt in buttonHolder.transform)
{
GameObject btGO = bt.gameObject;
if (!btGO.GetComponentInChildren<ButtomHandler>().onHover && bt == minButton) {
//Magnify
}
else if (bt != minButton && btGO.GetComponentInChildren<ButtomHandler>().onHover)
{
//minify
}
}
}
else {
activateButtonMenu();
}
}
//dis-hover all button if leave touch pad
if (device.GetTouchUp(SteamVR_Controller.ButtonMask.Touchpad)) {
//Hover the closest button
foreach (Transform bt in buttonHolder.transform)
{
GameObject btGO = bt.gameObject;
if (btGO.GetComponentInChildren<ButtomHandler>().onHover)
{
//minify
}
}
}
I'm quite stucked here, Any help would really be appreciated
"the closest angler difference with (touchPadAngle)"
shouldn't you consider more than one axis for a radial dial?

Farseer/XNA Assertion Failed, Vector2 position for body modified by camera matrix

I created a camera with a matrix and used it to move the view point in 2D. Basically I started from this template:
http://torshall.se/?p=272
I also had in one of my class, a simple code to spawn boxs with the mouse:
public void CreateBodies()
{
mouse = Mouse.GetState();
if (mouse.RightButton == ButtonState.Pressed)
{
Bodies += 1;
if (Bodies >= MaxBodies)
Bodies = 0;
rectBody[Bodies] = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(rectangle.Width), ConvertUnits.ToSimUnits(rectangle.Height), 1);
rectBody[Bodies].Position = ConvertUnits.ToSimUnits(mouse.X, mouse.Y);
rectBody[Bodies].BodyType = BodyType.Dynamic;
}
}
This Worked perfectly fine but when I moved the ''camera'' the mouse didn't change in the right location, Si I did this little modification in game1.cs and in my method to have the world coord. of my mouse:
mouse = Mouse.GetState();
Matrix inverse = Matrix.Invert(camera.transform);
Vector2 mousePos = Vector2.Transform(new Vector2(mouse.X, mouse.Y), inverse);
TE.CreateBodies(mousePos);
public void CreateBodies(Vector2 mousePosition)
{
mouse = Mouse.GetState();
MousePosition = mousePosition;
if (mouse.RightButton == ButtonState.Pressed)
{
Bodies += 1;
if (Bodies >= MaxBodies)
{
Bodies = 0;
}
rectBody[Bodies] = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(rectangle.Width), ConvertUnits.ToSimUnits(rectangle.Height), 1);
rectBody[Bodies].BodyType = BodyType.Dynamic;
rectBody[Bodies].Position = ConvertUnits.ToSimUnits(MousePosition);
}
}
Now this is supposed to give me the world coords. of my mouse, but I have a problem, when I run the program and click somewhere on the screen to create a box I get this error:
http://img68.xooimage.com/files/6/a/4/bob-2c526f4.png
What's going on? :/
Edit:
This is at the line 439 of body.cs:
Debug.Assert(!float.IsNaN(value.X) && !float.IsNaN(value.Y));

Resources