this is what i'm trying to accomplish;
With a click on a movieclip (cannon_mc)
a shot is being fired (ball_mc)
The longer mouse is down, the speed of wich the ball is fired with should increase.
My question to you is;
What is the most efficient way to accomplish this?
With a timer or something like this;
var isMouseDown:Boolean = false;
var speed= 10;
myCannon.addEventListener(MouseEvent.MOUSE_DOWN,buttonPressed);
function buttonPressed(event:MouseEvent){
//trace("down");
isMouseDown == true;
if(isMouseDown == false)
{
speed == +1
}
}
The MOUSE_DOWN event is only fired once. To get the effect you want you need the combo of MOUSE_DOWN and MOUSE_UP Event Handlers.
You can set a variable to true in the MOUSE_DOWN event alongwith the current timestamp from flash.utils.getTimer()
Then on MOUSE_UP, if the variable you set in MOUSE_DOWN is true, you compute the time elapsed and set the power accordingly.
Example:
var isMouseDown:Boolean = false;
var mouseDownBegin:int;
var speed = 10;
var speed_inc = 2; // give it in per second
var speed_max = 100; // max speed possible
// add event handlers
myCannon.addEventListener(MouseEvent.MOUSE_DOWN, buttonPressed);
myCannon.addEventListener(MouseEvent.MOUSE_UP, buttonReleased);
function buttonPressed(event:MouseEvent){
isMouseDown = true;
mouseDownBegin = flash.utils.getTimer();
}
function buttonReleased(event:MouseEvent){
if(isMouseDown == true){
// get time between press and release
var timeElapsed = flash.utils.getTimer() - mouseDownBegin;
// reset isMouseDown
isMouseDown = false;
// compute speed
speed += int(Math.floor(speed_inc * (timeElapsed / 1000.0)));
speed = Math.min(speed, speed_max);
// code to fire ball with new speed
// .......
}
}
You can also add an ENTER_FRAME event and animate a power gauge or something for visual effect
Update
As pointed to by The_asMan, MOUSE_UP event will not fire if the mouse is dragged and released Outside the stage. To handle this case add and event listener for MOUSE_LEAVE event with the callback as the copy of buttonReleased function but which takes an Event object:
function buttonReleasedOutsideStage(event:Event){
if(isMouseDown == true){
// get time between press and release
var timeElapsed = flash.utils.getTimer() - mouseDownBegin;
// reset isMouseDown
isMouseDown = false;
// compute speed
speed += int(Math.floor(speed_inc * (timeElapsed / 1000.0)));
speed = Math.min(speed, speed_max);
// code to fire ball with new speed
// .......
}
}
stage.addEventListener(Event.MOUSE_LEAVE, buttonReleasedOutsideStage);
(in very short pseudocode)
Write some event handlers:
onMouseDown: sets flag _mouseDown, set power to zero
onFrame: if (_mouseDown) power++;
onMouseUp: clears flag _mouseDown and fires ball with accumulated power
Framerate independent version:
onMouseDown: _loadStart = getTimer(); _mouseDown = true; _power = 0;
onFrame: if (_mouseDown) delta = getTimer() - _loadStart; _power += delta;
onMouseUp: shot the ball with _power, _mouseDown = false;
Related
I'm currently working on a project in which I want an image to pop up after 3 seconds. Once that image has popped up the user has to click on the image to make a "done" image pop up that will disappear automatically after 3 seconds.
I've got most of it working except for the disappearing part. Does anyone know how I can time the image to disappear after 3 seconds?
PImage medic;
PImage medicD;
float time;
float startTime;
final int waitpopup = 3000;
final int DISPLAY_DURATION = 3000;
boolean showimage = true;
boolean showclock = true;
boolean showimagedone = true;
boolean hasClicked;
Clock clock;
void setup (){
size (1080, 1920);
medic = loadImage("medic.png");
medicD = loadImage("medicD.png");
clock = new Clock(width /2, height /2);
time = millis();
}
void draw() {
background (0);
imageMode(CENTER);
if (showclock) clock.display();
if (showimage && millis() - time > waitpopup) {
image(medic, width/2, height/2, 540, 540);
} if (hasClicked == true) {
showimage = false;
image(medicD, width/2, height/2, 540, 540);
} if (millis() > startTime + DISPLAY_DURATION) {
showimagedone = false;
}
}
void mousePressed() {
hasClicked = true;
startTime = time;
}
You can use the millis() function or the frameCount variable to check how much time has gone by, then do something after X seconds or after X frames.
You're already doing some of the work with the showimagedone variable, but you need to use that variable to conditionally draw your image.
I recommend starting with a simpler example and getting that working. Here's one example:
int clickedFrame;
boolean on = false;
int duration = 60;
void draw(){
if(on){
background(255);
if(frameCount > clickedFrame + duration){
on = false;
}
}
else{
background(0);
}
}
void mousePressed(){
clickedFrame = frameCount;
on = true;
}
This code show a white background for one second whenever the user clicks the mouse. You need to do something similar with your images.
Related posts:
How to make a delay in processing project?
How can I draw only every x frames?
Removing element from ArrayList every 500 frames
Timing based events in Processing
How to add +1 to variable every 10 seconds in Processing?
How to create something happen when time = x
making a “poke back” program in processing
Processing: How do i create an object every “x” time
Timer using frameRate and frame counter reliable?
Adding delay in Processing
Please also consult the Processing reference for more information.
If you still can't get it working, please post a MCVE (not your full project!) in a new question and we'll go from there. Good luck.
I have a unity game and in it, a rotating game object, which increases its speed when it is clicked.
My problem is that the game does not work as I want it to. Right now, if I click any part of the screen, it increases the game object's speed of rotation. On the other hand, if I keep my finger on the screen, the game object starts to slow down and then starts rotating in the opposite direction.
I want the rotation of the object to increase when I click on it, not just if I click on any part of the screen. Furthermore, I don't know why holding down reverses the direction of rotation.
var speed = 1;
var click = 0;
Screen.orientation = ScreenOrientation.LandscapeLeft;
function Update (){
{
transform.Rotate(0,0,speed);
}
if(Input.GetMouseButton(0))
{
if(speed != 0)
{
speed = 0;
} else {
click++;
speed = click;
}
You must use Input.GetMouseButtonUp or Input.GetMouseButtonDown, NOT A Input.GetMouseButton, this method used for clamping.
Try use this code:
var speed = 1;
var click = 0;
Screen.orientation = ScreenOrientation.LandscapeLeft;
function Update (){
{
transform.Rotate(0,0,speed);
}
if(Input.GetMouseButtonDown(0))
{
if(speed != 0)
{
speed = 0;
} else {
click++;
speed = click;
}
A few issues here:
Firstly:
To increase speed upon clicking on the object only, use raycasting from camera, and check if it hits your object. Your object needs need a collider component on it for this to work.
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Transform objectHit = hit.transform;
objectHit.Rotate(0,0,speed);
}
Refer to https://docs.unity3d.com/Manual/CameraRays.html -> Raycasting section, for more information.
Secondly:
Input.GetMouseButtonDown(..) // returns true at the instance your mouse button transits from up to down
Input.GetMouseButton(..) // returns true as long as your mouse button is held down
Use Input.GetMouseButtonDown(..) in your Update() method if you want to to do something when you click on it.
Subject: I have a stream (actually combined stream from Bacon.interval and buttons clicks EventStreams) wich fires ajax request and solve task of manual and automatic data refresh.
Problem: After manual events (buttons clicks) I need reset timer because two immediate updates looks ugly.
My solution: I've created my own Bacon.interval implementation where event polls can be reseted http://jsfiddle.net/cvvkxveq/1/:
Bacon.dynInterval = function(time,resetter){
if(!time) return Bacon.once(new Bacon.Error("Invalid args"));
var ivId, lastTime = Date.now();
return time < 1 ? Bacon.once(new Bacon.Error("Invalid time")) : Bacon.fromBinder(function(sink) {
function setUpInterval(){
if(ivId) clearInterval(ivId);
ivId = setInterval(function(){
var n = Date.now();
var tdx = n - lastTime;
lastTime = n;
sink(new Bacon.Next(tdx));
},time);
}
setUpInterval();
if(resetter) resetter.onValue(setUpInterval);
return function() {
clearInterval(ivId);
sink(new Bacon.End())
}
})
}
Question: Is such behaivour can be done without custom event stream?
Update (thanks #raimohanska's answer) basing on #raimohanska's answer I've also converded my ouUiE event sream (manualTriggerE) to property with initial value to accomplish immediate updates starts.
var quotesService = Bacon.constant({url:"quotes.php"});
var onUiE = $("#next_stock, #prev_stock, #refresh_quotes").clickE().map(".currentTarget.id");
var onUiP = onUiE.toProperty("");
var periodicUpdateE = onUiP.flatMapLatest(function(){ return Bacon.interval(3000)});
var manualPlusPeriodicP = onUiP.toEventStream().merge(periodicUpdateE);
var quotesStream = quotesService.sampledBy(manualPlusPeriodicP).ajax();
If you have a stream manualTriggerE, you can add periodic updates that are reseted on each manual trigger like this:
let periodicUpdateE = manualTriggerE.flatMapLatest(() => Bacon.interval(1000))
let manualPlusPeriodicE = manualTrigger.merge(periodicUpdateE)
The trick is flatMapLatest: it restarts the periodic updates whenever a manual trigger occurs.
I'm using Adobe Flash Professional CS6 to create the game. I'll post the code under. Be noticed that there are two symbol I've created using Flash that are not made by code. These symbols are the Crosshair symbol, and the Hitbox symbol. Basically, the objective of the game is to click the Hitbox symbol. My issue is that I am experiencing what seems to be bottlenecking issues. When I click the Hitbox symbol a lot of times with a fast timer the score doesn't register. I am pressuming that this comes from the (maybe) ineffective movement algorithm. But I can't really seem to find room for improvement. Some help would be appreciated.
Be noticed, I had to change the timer from Timer(1) to Timer(30). This made the bottlenecking issue a little bit better, but made the game less fluent.
Aah, and the reason as to why I am using the directionCheckerY and directionCheckerX variables is that I will later in the development add random movement. A random timer will change these to either 0 and 1, creating random movement.
import flash.events.MouseEvent;
import flash.events.TimerEvent;
// Variables
var directionCheckerX:int=0;
var directionCheckerY:int=0;
var pointChecker:int=0;
// Croshair
var crosshair:Crosshair = new Crosshair();
addChild(crosshair);
Mouse.hide();
function moveCrossEvent (evt: MouseEvent) {
crosshair.x = mouseX;
crosshair.y = mouseY;
evt.updateAfterEvent();
}
// Hitbox
var hitbox:Hitbox = new Hitbox();
addChild(hitbox);
hitbox.x=50;
hitbox.y=50;
// Timer
var myTimer:Timer = new Timer(30);
myTimer.addEventListener(TimerEvent.TIMER, timerEvent);
myTimer.start();
function timerEvent(evt:TimerEvent) {
// Border code (Keeps the Hitbox away from out of bounds)
if (hitbox.x <= 0) {
directionCheckerX = 1;
} else if (hitbox.x >= 550) {
directionCheckerX = 0;
}
if (directionCheckerX == 0) {
hitbox.x-=2;
} else {
hitbox.x+=2;
}
if (hitbox.y <= 0) {
directionCheckerY = 1;
} else if (hitbox.y >= 400) {
directionCheckerY = 0;
}
if (directionCheckerY == 0) {
hitbox.y-=2;
} else {
hitbox.y+=2;
}
}
// EventListeners
stage.addEventListener(MouseEvent.MOUSE_MOVE, moveCrossEvent);
hitbox.addEventListener(MouseEvent.CLICK, hitboxEvent);
stage.addEventListener(MouseEvent.CLICK, stageEvent);
function hitboxEvent (evt:MouseEvent) {
pointChecker+=1;
outputTxt.text = String(pointChecker);
evt.stopImmediatePropagation();
//evt.updateAfterEvent();
}
function stageEvent(evt:MouseEvent) {
pointChecker-=1;
outputTxt.text = String(pointChecker);
}
To be clear, I'm not a game developer.
Actually, sometimes there is no big difference between a Timer with 1 millisecond interval and another one with 30 milliseconds interval because it's depending on the SWF file's framerate or the runtime environment ... but here, what about using an Event.ENTER_FRAME event instead of a Timer ? because as Adobe said here about Timers versus ENTER_FRAME events :
Choose either timers or ENTER_FRAME events, depending on whether content is animated.
Timers are preferred over Event.ENTER_FRAME events for non-animated content that executes for a long time.
and in your case the content is animated (even if your game is still basic).
Then you can use a var to set the speed of your hitbox which you can update at any time :
var speed:int = 2;
function timerEvent(evt:TimerEvent): void
{
// ...
if (directionCheckerX == 0) {
hitbox.x -= speed;
} else {
hitbox.x += speed;
}
// ...
}
Hope that can help.
Can I call a function(one that will make another object visible/invisible) on a specific animation frame or time? I would like to have arrows describe the movement of the animation at certain times during the animation. While I can just make them visible when I start the animation and make them invisible when the animation stops, I would like to specify ranges inside the animation to do this
playPatientAnim: function (anim, callback) {
var pending = 1;
var me = this;
var finish = callback ? function () {
if (pending && !--pending) {
callback.call(me, anim);
}
} : null;
me.currentPatient.skinned.forEach(function (mesh) {
mesh.animations.forEach(function(anim){
anim.stop();
});
});
me.currentPatient.skinned.forEach(function (mesh) {
var animation = mesh.animations[anim];
animation.stop();
if (animation) {
pending++;
animation.onComplete = finish;
animation.play();
}
});
if (finish) {
finish();
}
}
You can make a mesh visible or invisible ( mesh.visible = false; //or true ). To change visibility at certain time you could use timestamp:
new Date().getTime() and calculate how you want to do the sequence of your animation.