SVG animation's 'onbegin' event not fired on IOS - ios

<svg xmlns="http://www.w3.org/2000/svg">
<title>On end test</title>
<circle r="50" cx="100" cy="100" style="fill: #F00">
<set attributeName="fill" attributeType="CSS" onbegin='alert("onbegin")'
onend='alert("onend")' to="#00F" begin="1s" dur="5s" />
</circle>
</svg>
you can try this code here
it looks onbegin event not work on the IOS device, dose anyone here has a clue?

#Rebert, you are right, but I found a another way to solve this problem in browsers which was not support begin/end event, here is the code:
window.XY = window.XY ? window.XY : {};
XY.svg = XY.svg ? XY.svg : {};
XY.svg.runtime_id = 0;
XY.svg.found_support_event = false;
XY.svg.SVG_Event_Compatibility = function(svg_object){
if(XY.svg.found_support_event) return;
if(XY.svg.runtime_id != 0) clearInterval(XY.svg.runtime_id);
var _animate_list = [];
var _animate_has_event_list = [];
_animate_list = svg_object.getElementsByTagName('animate');
if(_animate_list.length == 0){
return;
}else{
if(typeof _animate_list[0].onbegin !== 'undefined'){
XY.svg.found_support_event = true;
return;
}
}
var _length = _animate_list.length;
for(var i=0; i<_length; i++){
var _cur = _animate_list[i];
var _cur_obj = { target:_cur};
var _has_event = false;
var _begin_hold = _cur.getAttributeNode('onbegin');
var _end_hold = _cur.getAttributeNode('onend');
if(_begin_hold){
_cur_obj.begin = _begin_hold.value;
_cur_obj.duration = _cur.getSimpleDuration();
_has_event = true;
}
if(_end_hold){
_cur_obj.end = _end_hold.value;
_cur_obj.duration = _cur.getSimpleDuration();
_has_event = true;
}
if(_has_event){
//console.log(_cur_obj);
_animate_has_event_list.push(_cur_obj);
}
}
//console.log('start' ,_animate_has_event_list);
function Run(){
if(_animate_has_event_list.length == 0){
clearInterval(XY.svg.runtime_id);
}
var _length = _animate_has_event_list.length;
//console.log("==========================");
for(var i=0; i<_animate_has_event_list.length; i++){
var _cur_obj = _animate_has_event_list[i];
if(_cur_obj.begin == null && _cur_obj.end == null){
//console.log('remove' ,_animate_has_event_list.splice(i,1));
continue;
}
var _start_time = _cur_obj.target.getStartTime();
var _current_time = _cur_obj.target.getCurrentTime();
//console.log(_start_time, _current_time, _cur_obj.duration ,isNaN(_start_time) ,_start_time < Infinity
// ,!isNaN(_start_time) && _start_time < Infinity && _start_time > _current_time
// ,!isNaN(_start_time) && _start_time < Infinity && (_current_time - _start_time > _cur_obj.duration));
if(_cur_obj.begin){
if(!isNaN(_start_time) && _start_time < Infinity && _start_time < _current_time){
var _begin = eval(_cur_obj.begin);
if(typeof _begin === 'function'){
_begin.apply(_cur_obj.target);
}
_cur_obj.begin = null;
}
}
if(_cur_obj.end){
if(!isNaN(_start_time) && _start_time < Infinity && (_current_time - _start_time > _cur_obj.duration)){
var _end = eval(_cur_obj.end);
if(typeof _end === 'function'){
_end.apply(_cur_obj.target);
}
_cur_obj.end = null;
}
}
}
//console.log('runtime', _animate_has_event_list);
}
XY.svg.runtime_id = setInterval(Run, 100);
}

This is not implemented in webkit currently. You'd have write a patch for bug 81995 or pay someone else to do it for you.

Related

Marking text in a html document

Lets say I have the following markup:
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Some title</h1>
<p>First paragraph</p>
<p>Second paragraph</p>
</body>
<html>
I need to mark some parts of the text, namely "irst paragraph secon"
It would look something like this:
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Some title</h1>
<p>F
<mark>
irst paragraph</p><p>Secon
</mark>
d paragraph</p>
</body>
<html>
But the problem is be the html markup would be broken. The more complex the markup, the more problems this approach would have.
Question:
Looking for ideas on how can I take the first HTML example and apply a function to return a html structure where "irst paragraph second" is specifically marked somehow.
What I currently have is:
the parent container of the string "First paragraph"
the text "irst paragraph second"
the offset of the text "irst" in "First paragraph"
If you want to highlight text in a document then this plug-in will be helpful for you.
https://github.com/julmot/jquery.mark
Example fiddle: https://jsfiddle.net/julmot/vpav6tL1/
Usage is as simple as:
$(".context").mark("keyword");
In principle you have to:
split the documents into words
identify the first word by parent element
skip the offset
mark matching words
Making changes at word level will prevent you from breaking the markup.
I added a working example bellow. However I am not sure that it will work with all browsers.
Some of the functions like mergeWords are not used in the example but I included them because they can prove useful.
var splittedToWords = false;
function ignore(el) {
return (el.nodeType == 8) ||
(el.tagName == "BLOCKQUOTE") ||
(el.tagName == "SCRIPT") ||
(el.tagName == "DIV") ||
(!el.hasChildNodes() && el.textContent.match(/\S+/) == null);
}
function splitToWords(el) {
if (el.hasChildNodes()){
var count = el.childNodes.length;
for (var i = count - 1; i >= 0; i--) {
var node = el.childNodes[i];
if (!ignore(node))
splitToWords(node);
}
}
else { //text node
var words = el.textContent.match(/(\S+\s*)/g) || [];
var count = words.length;
var parentNode = el.parentNode;
for (var i = 0; i < count; i++) {
var wordNode = document.createElement("span");
wordNode.className = "word";
wordNode.innerText = words[i];
wordNode.setAttribute["word-index"] = i;
parentNode.insertBefore(wordNode, el);
}
parentNode.removeChild(el);
}
splittedToWords = true;
}
function unwrap(element) {
var next = element.nextSibling;
var parent = element.parentNode;
parent.removeChild(element);
var current;
var frag = document.createDocumentFragment();
do {
current = element.nextSibling;
frag.insertBefore(element, null);
} while ((element = current));
parent.insertBefore(frag, next);
}
function mergeWords(el) {
var words = document.getElementsByClassName("word");
count = words.length;
if (count > 0)
for (var i = 0; i < count; i++)
uwrap(words[i]);
}
function markWord(el, pos, len) {
var text = el.innerText;
var pre = text.substr(0, pos);
var mark = '<mark>' + text.substr(pos, len) + '</mark>';
var post = text.substring(pos + len, text.length);
el.innerHTML = pre + mark + post;
}
function mark(element, offset, text) {
if (!splittedToWords) {
var body = document.body;
splitToWords(body);
}
var words = document.getElementsByClassName("word");
var wordsCount = words.length;
var first = null;
for (var i = 0; i < wordsCount; i++ ) {
if (words[i].parentElement == element) {
first = i;
break;
}
}
done = false;
var i = first;
var pos = 0;
do {
var word = words[i];
var wordLength = word.innerText.length;
if (offset > pos + wordLength) {
i++;
pos += wordLength;
continue;
}
else {
done = true;
}
} while (!done);
var tWords = text.match(/(\S+\s*)/g) || [];
var tWordsCount = tWords.length;
if (tWordsCount == 0)
return;
for (var ti = 0; ti < tWordsCount; ti++) {
var wordEl = words[i++];
var word = wordEl.innerText;
var tWord = tWords[ti].trim();
var pos = word.indexOf(tWord);
if (pos == -1)
continue; //or maybe return.
markWord(wordEl, pos, tWord.length);
}
}
var e = document.getElementById("e");
//do the magic
mark(e, 1, 'irst paragraph Second');
<h1>Some title</h1>
<p id="e">First paragraph</p>
<p>Second paragraph</p>

jQuery datetimepicker: disable time

I am using the XDSoft jQuery datetimepicker in my app (Ruby on Rails 4 (just for information, not using bootstrap datetimepicker)).
I was wondering if there is a way to disable/deactivate a specific time at a specific date, for example disable only 17:00 on 12/17/2014?
disabledDates: ['...'] disables a specific date.
I tried disabledDateTimes and disabledTimes but they don't work.
Thanks.
Here is one example of how this can be done using the XDSoft DateTimePicker you are asking about.
I have a specificDates array which you can use to add dates you want to target.
I also have an hoursToTakeAway multi dimensional array which corresponds with the specificDates array where you can specify the hours to take away.
HTML
<input class="eventStartDate newEventStart eventEditDate startTime eventEditMetaEntry" id="from_date" name="from_date" placeholder="Start date and time" readonly="readonly" type="text" />
Javascript
var specificDates = ['24/12/2014','17/12/2014'];
var hoursToTakeAway = [[14,15],[17]];
$('#from_date').datetimepicker({
format:'d.m.Y H:i',
timepicker: true,
lang: 'en',
onGenerate:function(ct,$i){
var ind = specificDates.indexOf(ct.dateFormat('d/m/Y'));
$('.xdsoft_time_variant .xdsoft_time').show();
if(ind !== -1) {
$('.xdsoft_time_variant .xdsoft_time').each(function(index){
if(hoursToTakeAway[ind].indexOf(parseInt($(this).text())) !== -1) {
$(this).hide();
}
});
}
}
});
Example
Fiddle
Basically I am taking advantage of the onGenerate event which happens after each calendar has been rendered. Then I am checking to see if the date matches the specified day and if it does, we iterate through all the time elements and hide the ones specified for the specific date.
Updated Fiddle implementing disable.
Fiddle 2
This code is working for me:
var specificDates = ['24/12/2014','17/12/2014'];
var hoursToTakeAway = [[14,15],[17]];
$('#from_date').datetimepicker({
format:'d.m.Y H:i',
timepicker: true,
lang: 'en',
onGenerate:function(ct,$i){
var ind = specificDates.indexOf(ct.dateFormat('d/m/Y'));
$('.xdsoft_time_variant .xdsoft_time').show();
if(ind !== -1) {
$('.xdsoft_time_variant .xdsoft_time').each(function(index){
if(hoursToTakeAway[ind].indexOf(parseInt($(this).text())) !== -1) {
$(this).hide();
}
});
}
}
});
If someone still need solution, i write code to disable ranges of time in jquery-ui-datepicker.
First I need to init ranges, that will be disabled at current date:
dateObj1 = new Date(2016,6,22,0);
dateObj2 = new Date(2016,6,27,10);
diap1 = [dateObj1, dateObj2];
dateObj1 = new Date(2016,6,27,13);
dateObj2 = new Date(2016,6,27,14);
diap2 = [dateObj1, dateObj2];
dateObj1 = new Date(2016,6,27,20);
dateObj2 = new Date(2016,6,29,10);
diap3 = [dateObj1, dateObj2];
dateObj1 = new Date(2016,6,27,0);
dateObj2 = new Date(2016,6,27,13);
diap4 = [dateObj1, dateObj2];
dateObj1 = new Date(2016,7,02,4);
dateObj2 = new Date(2016,7,02,4,59);
diap5 = [dateObj1, dateObj2];
diapazons = [diap1,diap2,diap3,diap4,diap5];
Then I need function, to proceed this ranges, detect intersections and create ranges, that will be displayed:
function getAvailableTimes(restricts, curr_year, curr_month, cur_day)
{
day_diaps = [[new Date(curr_year,curr_month,cur_day,0), new Date(curr_year,curr_month,cur_day,23,59,59)]];
restricts.forEach(function(item, i, arr) {
day_diaps.forEach(function(day_diap, i_d, arr_d) {
//console.log('day = '+day_diap.toString());
if (day_diap[0] >= item[1])
{
//console.log(i+' раньше');
}
else if (day_diap[1] <= item[0])
{
//console.log(i+' позже');
}
else if (day_diap[0] >= item[0] && day_diap[1] <= item[1])
{
//console.log(i+' закрыт полностью');
arr_d.splice(i_d,1);
}
else if (day_diap[0] >= item[0] && day_diap[1] >= item[1])
{
day_diap[0] = item[1];
//console.log(i+' ранее перекрытие, начало смещено на '+ day_diap.toString());
}
else if (day_diap[0] <= item[0] && day_diap[1] <= item[1])
{
day_diap[1] = item[0];
//console.log(i+' позднее перекрытие, конец смещен на '+ day_diap.toString());
}
else if (day_diap[0] <= item[0] && day_diap[1] >= item[1])
{
new_diap = [item[1],day_diap[1]];
arr_d.push(new_diap);
day_diap[1] = item[0];
//console.log(i+' restrict полностью умещается в диапазон '+ day_diap.toString());
//console.log(i+' добавлен диапазон '+ new_diap.toString());
}
});
});
return day_diaps;
}
And code in of datetimepicker:
<input type="text" id="default_datetimepicker"/>
<script>
$.datetimepicker.setLocale('ru');
var dates_to_disable = ['30-07-2016','31-07-2016','04-08-2016'];
$('#default_datetimepicker').datetimepicker({
formatTime:'H:i',
lang: "ru",
defaultTime:"10:00",
formatDate:'d-m-Y',
todayButton: "true",
minDate:'01-01--1970', // yesterday is minimum date
disabledDates:dates_to_disable,
onGenerate:function(ct,i){
var dates = jQuery(this).find('.xdsoft_date ');
$.each(dates, function(index, value){
year = jQuery(value).attr('data-year');
month = jQuery(value).attr('data-month');
date = jQuery(value).attr('data-date');
diaps = getAvailableTimes(diapazons,year,month,date);
net_nihrena = true;
diaps.forEach(function(day_diap, i_d, arr_d) {
net_nihrena = false;
});
if (net_nihrena)
{
jQuery(value).addClass('xdsoft_disabled');
//jQuery(value).addClass('xdsoft_restricted');
}
});
cur_date = ct;
diaps = getAvailableTimes(diapazons,ct.getFullYear(),ct.getMonth(),ct.getDate());
var times = jQuery(this).find('.xdsoft_time ');
$.each(times, function(index){
var hour = $(this).attr('data-hour');
var minute = $(this).attr('data-minute');
cur_date.setHours(hour,minute,0);
net_takogo_vremeni = true;
diaps.forEach(function(day_diap, i_d, arr_d) {
if ((day_diap[0] < cur_date && day_diap[1] > cur_date) || hour==0)
{
net_takogo_vremeni = false;
}
});
if (net_takogo_vremeni)
{
$(this).addClass('xdsoft_disabled');
//$(this).addClass('xdsoft_restricted');
}
});
},
onSelectDate : function(ct) {
}
});
</script>

1151: A conflict exists with definition i in namespace internal

im new in action scripts and flash, i need some help with this code i couldnt find whats wrong with it, it gives this error:1151: A conflict exists with definition i in namespace internal.(var i:Number = 0;)
stop();
menu_item_group.menu_item._visible = false;
var spacing:Number = 5;
var total:Number = menu_label.length;
var distance_y:Number = menu_item_group.menu_item._height + spacing;
var i:Number = 0;
for( ; i < total; i++ )
{
menu_item_group.menu_item.duplicateMovieClip("menu_item"+i, i);
menu_item_group["menu_item"+i]._x = menu_item._x;
menu_item_group["menu_item"+i]._y = i * distance_y;
menu_item_group["menu_item"+i].over = true;
menu_item_group["menu_item"+i].item_text.text = menu_label[i];
menu_item_group["menu_item"+i].item_url = menu_url[i];
menu_item_group["menu_item"+i].onRollOver = function()
{
this.over = false;
}
menu_item_group["menu_item"+i].onRollOut = menu_item_group["menu_item"+i].onDragOut = function()
{
this.over = true;
}
menu_item_group["menu_item"+i].onRelease = function()
{
getURL(this.item_url);
}
menu_item_group["menu_item"+i].onEnterFrame = function()
{
if( this.over == true ) this.prevFrame();
else this.nextFrame();
}
}
thanks for your help!
Check your code. The variable i has been declared in the code already.

Actionscript3 ArgumentError: Error #2109:

Making a touch based platform game based in actionscript 3 using Gary Rosenzweig's game as a basis, all was going well until today, I've been trying to swap out floor objects etc without changing much of the actionscript at all and I have the following error.
ArgumentError: Error #2109: Frame label jump not found in scene jump.
at flash.display::MovieClip/gotoAndStop()
at PlatformGame/moveCharacter()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:418]
at PlatformGame/moveEnemies()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:314]
at PlatformGame/gameLoop()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:303]
This also seems to cause problems with collision detection.
The code is as follows. (not i have not changed the scene or label names from the originals but it still shows the error).
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class PlatformGame extends MovieClip {
// movement constants
static const gravity:Number = .004;
// screen constants
static const edgeDistance:Number = 100;
public var rightButton:SimpleButton;
// object arrays
private var fixedObjects:Array;
private var otherObjects:Array;
// hero and enemies
private var hero:Object;
private var enemies:Array;
// game state
private var playerObjects:Array;
private var gameScore:int;
private var gameMode:String = "start";
private var playerLives:int;
private var lastTime:Number = 0;
// start game
public function startPlatformGame() {
playerObjects = new Array();
gameScore = 0;
gameMode = "play";
playerLives = 3;
}
// start level
public function startGameLevel() {
// create characters
createHero();
addEnemies();
// examine level and note all objects
examineLevel();
// add listeners
this.addEventListener(Event.ENTER_FRAME,gameLoop);
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
gamelevel["rButton"].addEventListener(TouchEvent.TOUCH_BEGIN,touchRight);
gamelevel["rButton"].addEventListener(TouchEvent.TOUCH_END,touchRightReleased);
gamelevel["lButton"].addEventListener(TouchEvent.TOUCH_BEGIN,touchLeft);
gamelevel["lButton"].addEventListener(TouchEvent.TOUCH_END,touchLeftReleased);
gamelevel["jButton"].addEventListener(TouchEvent.TOUCH_BEGIN,jump);
gamelevel["jButton"].addEventListener(TouchEvent.TOUCH_END,jumpReleased);
trace("hi"+gamelevel["rButton"]);
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// start level
public function startGameLevelHarder() {
// create characters
createHero();
addHardEnemies();
// examine level and note all objects
examineLevel();
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// start level
public function startGameLevelHardest() {
// create characters
createHero();
addHardestEnemies();
// examine level and note all objects
examineLevel();
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// creates the hero object and sets all properties
public function createHero() {
hero = new Object();
hero.mc = gamelevel.hero;
hero.dx = 0.0;
hero.dy = 0.0;
hero.inAir = false;
hero.direction = 0;
hero.animstate = "stand";
hero.walkAnimation = new Array(2,3,4,5,6,7,8);
hero.animstep = 0;
hero.jump = false;
hero.moveLeft = false;
hero.moveRight = false;
hero.jumpSpeed = .8;
hero.walkSpeed = .15;
hero.width = 15.0;
hero.height = 35.0;
hero.startx = hero.mc.x;
hero.starty = hero.mc.y;
}
// finds all enemies in the level and creates an object for each
public function addEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .08;
enemy.width = 30.0;
enemy.height = 30.0;
enemies.push(enemy);
i++;
}
}
// finds all enemies in the level and creates an object for each
public function addHardEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .15;
enemy.width = 56.0;
enemy.height = 80.0;
enemies.push(enemy);
i++;
}
}
// finds all enemies in the level and creates an object for each
public function addHardestEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .25;
enemy.width = 40.0;
enemy.height = 40.0;
enemies.push(enemy);
i++;
}
}
// look at all level children and note walls, floors and items
public function examineLevel() {
fixedObjects = new Array();
otherObjects = new Array();
for(var i:int=0;i<this.gamelevel.numChildren;i++) {
var mc = this.gamelevel.getChildAt(i);
// add floors and walls to fixedObjects
if ((mc is Floor) || (mc is Wall) || (mc is ground1) || (mc is wall1) || (mc is ledge1) || (mc is ledge2) || (mc is rock) ||(mc is rocktip)) {
var floorObject:Object = new Object();
floorObject.mc = mc;
floorObject.leftside = mc.x;
floorObject.rightside = mc.x+mc.width;
floorObject.topside = mc.y;
floorObject.bottomside = mc.y+mc.height;
fixedObjects.push(floorObject);
// add treasure, key and door to otherOjects
} else if ((mc is Treasure) || (mc is Key) || (mc is Door) || (mc is Chest)) {
otherObjects.push(mc);
}
}
}
// note key presses, set hero properties
public function touchRight(event:TouchEvent) {
trace("touchRight");
hero.moveRight = true;
}
public function touchRightReleased(event:TouchEvent) {
hero.moveRight = false;
}
public function touchLeft(event:TouchEvent) {
hero.moveLeft = true;
}
public function touchLeftReleased(event:TouchEvent) {
hero.moveLeft = false;
}
public function jump(event:TouchEvent) {
if (!hero.inAir) {
hero.jump = true;
}
}
public function jumpReleased(event:TouchEvent) {
if (!hero.inAir) {
hero.jump = false;
}
}
// note key presses, set hero properties
//public function keyDownFunction(event:KeyboardEvent) {
//if (gameMode != "play") return; // don't move until in play mode
//if (event.keyCode == 37) {
//hero.moveLeft = true;
//} else if (event.keyCode == 39) {
//hero.moveRight = true;
//} else if (event.keyCode == 32) {
//if (!hero.inAir) {
//hero.jump = true;
//}
//}
//}
//public function keyUpFunction(event:KeyboardEvent) {
//if (event.keyCode == 37) {
//hero.moveLeft = false;
//} else if (event.keyCode == 39) {
//hero.moveRight = false;
//}
//}
// perform all game tasks
public function gameLoop(event:Event) {
// get time differentce
if (lastTime == 0) lastTime = getTimer();
var timeDiff:int = getTimer()-lastTime;
lastTime += timeDiff;
// only perform tasks if in play mode
if (gameMode == "play") {
moveCharacter(hero,timeDiff);
moveEnemies(timeDiff);
checkCollisions();
scrollWithHero();
}
}
// loop through all enemies and move them
public function moveEnemies(timeDiff:int) {
for(var i:int=0;i<enemies.length;i++) {
// move
moveCharacter(enemies[i],timeDiff);
// if hit a wall, turn around
if (enemies[i].hitWallRight) {
enemies[i].moveLeft = true;
enemies[i].moveRight = false;
} else if (enemies[i].hitWallLeft) {
enemies[i].moveLeft = false;
enemies[i].moveRight = true;
}
}
}
// primary function for character movement
public function moveCharacter(char:Object,timeDiff:Number) {
if (timeDiff < 1) return;
// assume character pulled down by gravity
var verticalChange:Number = char.dy*timeDiff + timeDiff*gravity;
if (verticalChange > 15.0) verticalChange = 15.0;
char.dy += timeDiff*gravity;
// react to changes from key presses
var horizontalChange = 0;
var newAnimState:String = "stand";
var newDirection:int = char.direction;
if (char.moveLeft) {
// walk left
horizontalChange = -char.walkSpeed*timeDiff;
newAnimState = "walk";
newDirection = -1;
} else if (char.moveRight) {
// walk right
horizontalChange = char.walkSpeed*timeDiff;
newAnimState = "walk";
newDirection = 1;
}
if (char.jump) {
// start jump
char.jump = false;
char.dy = -char.jumpSpeed;
verticalChange = -char.jumpSpeed;
newAnimState = "jump";
}
// assume no wall hit, and hanging in air
char.hitWallRight = false;
char.hitWallLeft = false;
char.inAir = true;
// find new vertical position
var newY:Number = char.mc.y + verticalChange;
// loop through all fixed objects to see if character has landed
for(var i:int=0;i<fixedObjects.length;i++) {
if ((char.mc.x+char.width/2 > fixedObjects[i].leftside) && (char.mc.x-char.width/2 < fixedObjects[i].rightside)) {
if ((char.mc.y <= fixedObjects[i].topside) && (newY > fixedObjects[i].topside)) {
newY = fixedObjects[i].topside;
char.dy = 0;
char.inAir = false;
break;
}
}
}
// find new horizontal position
var newX:Number = char.mc.x + horizontalChange;
// loop through all objects to see if character has bumped into a wall
for(i=0;i<fixedObjects.length;i++) {
if ((newY > fixedObjects[i].topside) && (newY-char.height < fixedObjects[i].bottomside)) {
if ((char.mc.x-char.width/2 >= fixedObjects[i].rightside) && (newX-char.width/2 <= fixedObjects[i].rightside)) {
newX = fixedObjects[i].rightside+char.width/2;
char.hitWallLeft = true;
break;
}
if ((char.mc.x+char.width/2 <= fixedObjects[i].leftside) && (newX+char.width/2 >= fixedObjects[i].leftside)) {
newX = fixedObjects[i].leftside-char.width/2;
char.hitWallRight = true;
break;
}
}
}
// set position of character
char.mc.x = newX;
char.mc.y = newY;
// set animation state
if (char.inAir) {
newAnimState = "";
}
char.animstate = newAnimState;
// move along walk cycle
if (char.animstate == "walk") {
char.animstep += timeDiff/60;
if (char.animstep > char.walkAnimation.length) {
char.animstep = 0;
}
char.mc.gotoAndStop(char.walkAnimation[Math.floor(char.animstep)]);
// not walking, show stand or jump state
} else {
char.mc.gotoAndStop(char.animstate);
}
// changed directions
if (newDirection != char.direction) {
char.direction = newDirection;
char.mc.scaleX = char.direction*1.35;
}
}
// scroll to the right or left if needed
public function scrollWithHero() {
var stagePosition:Number = gamelevel.x+hero.mc.x;
var rightEdge:Number = stage.stageWidth-edgeDistance;
var leftEdge:Number = edgeDistance;
if (stagePosition > rightEdge) {
gamelevel.x -= (stagePosition-rightEdge);
gamelevel["rButton"].x += (stagePosition-rightEdge);
gamelevel["lButton"].x += (stagePosition-rightEdge);
gamelevel["jButton"].x += (stagePosition-rightEdge);
if (gamelevel.x < -(gamelevel.width-stage.stageWidth)) gamelevel.x = -(gamelevel.width-stage.stageWidth);
}
if (stagePosition < leftEdge) {
gamelevel.x += (leftEdge-stagePosition);
gamelevel["rButton"].x -= (leftEdge-stagePosition);
gamelevel["lButton"].x -= (leftEdge-stagePosition);
gamelevel["jButton"].x -= (leftEdge-stagePosition);
if (gamelevel.x > 0) gamelevel.x = 0;
}
}
// check collisions with enemies, items
public function checkCollisions() {
// enemies
for(var i:int=enemies.length-1;i>=0;i--) {
if (hero.mc.hitTestObject(enemies[i].mc)) {
// is the hero jumping down onto the enemy?
if (hero.inAir && (hero.dy > 0)) {
enemyDie(i);
} else {
heroDie();
}
}
}
// items
for(i=otherObjects.length-1;i>=0;i--) {
if (hero.mc.hitTestObject(otherObjects[i])) {
getObject(i);
}
}
}
// remove enemy
public function enemyDie(enemyNum:int) {
var pb:PointBurst = new PointBurst(gamelevel,"Got Em!",enemies[enemyNum].mc.x,enemies[enemyNum].mc.y-20);
gamelevel.removeChild(enemies[enemyNum].mc);
enemies.splice(enemyNum,1);
}
// enemy got player
public function heroDie() {
// show dialog box
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
if (playerLives == 0) {
gameMode = "gameover";
dialog.message.text = "Game Over!";
} else {
gameMode = "dead";
dialog.message.text = "He Got You!";
playerLives--;
}
hero.mc.gotoAndPlay("die");
}
// player collides with objects
public function getObject(objectNum:int) {
// award points for treasure
if (otherObjects[objectNum] is Treasure) {
var pb:PointBurst = new PointBurst(gamelevel,100,otherObjects[objectNum].x,otherObjects[objectNum].y);
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
addScore(100);
// got the key, add to inventory
} else if (otherObjects[objectNum] is Key) {
pb = new PointBurst(gamelevel,"Got Key!" ,otherObjects[objectNum].x,otherObjects[objectNum].y);
playerObjects.push("Key");
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
// hit the door, end level if hero has the key
} else if (otherObjects[objectNum] is Door) {
if (playerObjects.indexOf("Key") == -1) return;
if (otherObjects[objectNum].currentFrame == 1) {
otherObjects[objectNum].gotoAndPlay("open");
levelComplete();
}
// got the chest, game won
} else if (otherObjects[objectNum] is Chest) {
otherObjects[objectNum].gotoAndStop("open");
gameComplete();
}
}
// add points to score
public function addScore(numPoints:int) {
gameScore += numPoints;
scoreDisplay.text = String(gameScore);
}
// update player lives
public function showLives() {
livesDisplay.text = String(playerLives);
}
// level over, bring up dialog
public function levelComplete() {
gameMode = "done";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "Level Complete!";
}
// game over, bring up dialog
public function gameComplete() {
gameMode = "gameover";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "You Got the Treasure!";
}
// dialog button clicked
public function clickDialogButton(event:MouseEvent) {
removeChild(MovieClip(event.currentTarget.parent));
// new life, restart, or go to next level
if (gameMode == "dead") {
// reset hero
showLives();
hero.mc.x = hero.startx;
hero.mc.y = hero.starty;
gameMode = "play";
} else if (gameMode == "gameover") {
cleanUp();
gotoAndStop("start");
} else if (gameMode == "done") {
cleanUp();
nextFrame();
}
// give stage back the keyboard focus
stage.focus = stage;
}
// clean up game
public function cleanUp() {
removeChild(gamelevel);
this.removeEventListener(Event.ENTER_FRAME,gameLoop);
}
}
}
The error is with the following line and is occurring because the referenced MovieClip does not have a frame labelled "jump":
char.mc.gotoAndStop(char.animstate);
My guess is that you made a change to the MovieClip which contains your character and, in doing so, removed the label which the code above references.

Actionscript 2: Tween running extremely slow

I am using the following code to tween an movieclip once _global.choiceMade equals 1...
onClipEvent (load) {
import mx.transitions.Tween;
import mx.transitions.easing.*;
}
onClipEvent (enterFrame) {
if (_global.choiceMade == 1) {
var myTweenX:Tween = new Tween(this, "_x", mx.transitions.easing.Back.easeOut, this._x, -349, 0.5, True);
}
}
This is contained within each frame of the main timeline. The first time it runs fine but on the next frame it runs incredibly slow (takes about 12 seconds not 0.5 and is very choppy), if I then return to the first frame and run it again now this time it is extremely slow.
I can't work out why its doing this my CPU stays around 6-15% while its running so it can't be too demanding.
Updated to show rest of my code:
On main timeline have a frame each containing a movieclip. On the timeline of each of these movieclips contains:
//tint an object with a color just like Effect panel
//r, g, b between 0 and 255; amount between 0 and 100
Color.prototype.setTint = function(r, g, b, amount) {
var percent = 100-amount;
var trans = new Object();
trans.ra = trans.ga=trans.ba=percent;
var ratio = amount/100;
trans.rb = r*ratio;
trans.gb = g*ratio;
trans.bb = b*ratio;
this.setTransform(trans);
};//Robert Penner June 2001 - http://www.robertpenner.com
MovieClip.prototype.scaleXY = function(to){
this.onEnterFrame = function(){
this._alpha = to-(to-this._alpha)/1.2;
if(this._alpha > to-1 && this._alpha < to+1){
this._alpha = to;
delete this.onEnterFrame
}
}
}
scoreUpdated = 0;
Answer = 1;
_global.choiceMade = 0;
Buttons = new Array(this.buttonHolder.True, this.buttonHolder.False);
Answers = new Array(this.Correct, this.Wrong);
for (i=0; i<Answers.length; i++) {
Answers[i]._alpha = 0;
}
for (b=0; b<Buttons.length; b++) {
Buttons[b].thisValue = b;
}
In this movieclip there are two movieclip buttons (True and False) containing this code:
onClipEvent (enterFrame) {
this.onRollOver = function() {
this.gotoAndStop("over");
};
this.onRollOut = function() {
this.gotoAndStop("up");
};
this.onPress = function() {
this.gotoAndStop("down");
};
this.onReleaseOutside = function() {
this.gotoAndStop("up");
};
this.onRelease = function() {
this.gotoAndStop("down");
whichChoice = this;
_global.choiceMade = 1;
counter = 0;
};
if (_global.choiceMade == 1) {
this.enabled = false;
this._parent.scoreNow = _global.score;
this._parent.scoreOutOf = (this._parent._parent._currentframe)- 1 + ( _global.choiceMade);
if (thisValue == this._parent._parent.Answer && whichChoice == this) {
myColor = new Color(this);
myColor.setTint(0,204,0,13);
this._parent._parent.Answers[0]._alpha = 100;
this._parent._parent.Answers[0].scaleXY(100);
this.tick.swapDepths(1000);
if (counter == 0) {
_global.score++;
counter++;
}
}
else if (thisValue == this._parent._parent.Answer) {
myColor = new Color(this);
myColor.setTint(0,204,0,13);
this.tick.swapDepths(1000);
}
else if (whichChoice == this) {
this._parent._parent.Answers[1]._alpha = 100;
this._parent._parent.Answers[1].scaleXY(100);
myColor = new Color(this);
myColor.setTint(255,0,0,13);
this.cross.swapDepths(1000);
}
else {
myColor = new Color(this);
myColor.setTint(255,0,0,13);
myColor.setTint(255,0,0,13);
this.cross.swapDepths(1000);
}
}
}
The script at the top is on a movieclip these buttons are contained in called buttonHolder which does what it says, and tweens the buttons across the screen to reveal a next button once an answer is chosen.
From what I can see, as long as you have choiceMade == 1 you create a new effect! which is not ok. because in 1 sec at 15 fps you will have 15 tweens running :(
try yo set choiceMade = 0 or somehting else than 1
onClipEvent (enterFrame)
{
if (_global.choiceMade == 1)
{
_global.choiceMade = -1;
var myTweenX:Tween = new Tween(this, "_x", mx.transitions.easing.Back.easeOut, this._x, -349, 0.5, True);
}
}
Without seeing the rest of your code it's hard to see exactly what's going on. But it looks like you never change choiceMade and it continuously recreates the tween.
onClipEvent (enterFrame) {
if (_global.choiceMade == 1) {
var myTweenX:Tween = new Tween(this, "_x", mx.transitions.easing.Back.easeOut, this._x, -349, 0.5, True);
_global.choiceMade = 0;
}
}

Resources