How to call to external function in axios.spread function in VueJS? - vue.js

I can't call any external functions inside an axios promise. My error is
[Uncaught (in promise) TypeError: this.showNotification is not a function]
showNotification is an external function inside mixin but i can't call it in userCompInfo function
var mixin = {
methods: {
//function to get all user info
userInfo:function(){
//alert(localStorage.getItem("sessionKey"))
if(localStorage.getItem("sessionKey")==null)
session = "null";
else
session= localStorage.getItem("sessionKey");
return axios.post("/api/user/info",{
user_id:localStorage.getItem("userId"),
session_key:session
});
},
//function to get all competition info
compInfo:function()
{ //calling API competition info to get the avaliable competition for now
return axios.post("/api/competition/info",{
lang:source.lang
});
},
userCompInfo:function()
{
axios.all([this.userInfo(),this.compInfo()])
.then(axios.spread(function (user, comp){
if(comp.data.result.errorcode == 0)
{
source.competition = comp.data.competiton_detail;
}
//set the user id in local storage
localStorage.setItem("userId",user.data.user_info.user_id);
//check on session key to save it in local storage
if(user.data.user_info.session_key != "") // for testing
localStorage.setItem("sessionKey",user.data.user_info.session_key);
// get user data successfuly
if(user.data.result.errorcode == 0)
{ //set response data in user
source.user = user.data.user_info;
//to set this user status
this.renderUserInfo();
///////////
//source.competition.is_active=1;
//check on user status to show notification
if(source.user.vip && source.user.suspended)
{
this.showNotification(context.suspended_vip.title+" "+source.user.msisdn, context.suspended_vip.body,["btn_notifi_ok"]);
}
//check if this valid competition is active or not to show notification according to it and to user status
if(source.competition.is_active==1)
{
if(source.user.registered && newUser==1)
{
this.showNotification(context.registered_firstTime.title, context.registered_firstTime.body, ["btn_notifi_start_play"]);
}
else if(source.user.free && source.user.newFreeUser)
{
this.showNotification(context.freeUser_firstTime.title, context.freeUser_firstTime.body, ["btn_notifi_start_play"]);
}
}
}
}));
},
// function to show notification modal
showNotification:function(title, body, buttons)
{
//to hide all modal buttons first
$("#notification").find(".btn").hide();
//set the modal title
$("#notification_title").html(title);
//set the modal body
$("#notification_body").html(body);
//for on buttons array to show all buttons that we want
for(i=0;i<buttons.length;i++)
{
$("#notification").find("#"+buttons[i]).show();
}
//to display modal
$("#notification").modal("show");
},
//function to show the current user statue VIP, registered,free or suspended
renderUserInfo:function()
{ // intialize all flags of user status to false
source.user.vip = false;
source.user.registered = false;
source.user.free = false;
//check on user mode and set the according flag to it to true
if(source.user.sub_mode == "vip")
{
source.user.vip = true;
}
else if(source.user.sub_mode == "sub")
{
source.user.registered = true;
}
else
{
source.user.free = true;
}
},}}

This is a very common mistake. this in userCompInfo doesn't refer to the Vue because of they way you have written the callback.
In your code, make this change.
userCompInfo:function()
{
axios.all([this.userInfo(),this.compInfo()])
.then(axios.spread(function (user, comp){
// a bunch of code...
}.bind(this)));
},
Or
userCompInfo:function()
{
let self = this;
axios.all([this.userInfo(),this.compInfo()])
.then(axios.spread(function (user, comp){
// a bunch of code...
self.showNotification(...)
// some more code...
}));
},
See How to access the correct this inside a callback?

Related

How to make next song play once it is ended using Vue3 and Vuex Store

I want to implement a music player using Vue and the Vuex Store. I want that the next song starts playing when the current one ends. In normal js, I'd just use:
curr_track.addEventListener("ended", playNext)
where playNext would be a function I defined inside the same main.js file. When using Vue js and Vuex store, however, I can't do it the same. Any suggestions? I tried to pass the mutations function playNext inside of my store, but it did not work. Also, when calling
state.curr_track.duration = track.duration
I get the error:
Uncaught TypeError: Cannot set property duration of #<HTMLMediaElement> which has only a getter
How do I fix this? Thank you
The code is the following:
import { createStore } from 'vuex'
const store = createStore({
state() {
return {
curr_track: null,
track_list: null,
isPlaying: false,
}
},
mutations: {
setTrackList(state, tracks) {
state.track_list = tracks
},
/**
* Load the track and play it
* #param state - the state object
* #param state - the state object
*/
loadTrack(state, track) {
if (state.isPlaying) {
state.curr_track.pause()
}
// get track info
state.curr_track = new Audio()
state.curr_track.id = track.id
state.curr_track.src = track.file
state.curr_track.name = track.name
state.curr_track.artists = track.artists
// TODO: fix duration
// state.curr_track.duration = track.duration
state.curr_track.album_name = track.album.name
state.curr_track.album_cover = track.album.img_cover
state.curr_track.load()
// play track
this.commit('playTrack')
// TODO FIX
state.curr_track.addEventListener("ended", function() {
// if (state.track_list == null) {
// alert('Please select a track first')
// return []
// }
// if (state.track_list[state.track_list.length - 1]['id'] == state.curr_track.id) {
// console.log('last track, go to first')
// this.commit('loadTrack', state.track_list[0])
// } else {
// console.log('go to next track')
// let curr_idx = state.track_list.findIndex(track => track.id == state.curr_track.id)
// this.commit('loadTrack', state.track_list[curr_idx + 1])
// }
})
},
playTrack(state) {
// play loaded track
if (state.curr_track != null) {
state.curr_track.play();
state.isPlaying = true;
} else {
alert('Please select a track first')
}
},
pauseTrack(state) {
// Pause the loaded track
state.curr_track.pause();
state.isPlaying = false;
},
setVolume(state, value) {
// Set the volume
state.curr_track.volume = value
},
/**
* Play the next track: if the current track is the last track in the track list, then load the first track in the
* track list. Otherwise, load the next track in the track list
* #param state - the state object
*/
playNext(state) {
if (state.track_list == null) {
alert('Please select a track first')
return []
}
if (state.track_list[state.track_list.length - 1]['id'] == state.curr_track.id) {
console.log('last track, go to first')
this.commit('loadTrack', state.track_list[0])
} else {
console.log('go to next track')
let curr_idx = state.track_list.findIndex(track => track.id == state.curr_track.id)
this.commit('loadTrack', state.track_list[curr_idx + 1])
}
},
/**
* Play the previous track: if the current track is the first track in the track list, then load the last track in the
* track list. Otherwise, load the previous track in the track list
* #param state - the state object
*/
playPrevious(state) {
if (state.track_list[0]['id'] == state.curr_track.id) {
console.log('first track, got to last one')
this.commit('loadTrack', state.track_list[state.track_list.length - 1])
} else {
console.log('go to previous track')
let curr_idx = state.track_list.findIndex(track => track.id == state.curr_track.id)
this.commit('loadTrack', state.track_list[curr_idx - 1])
}
}
},
getters: {
getIsPlaying(state) {
return state.isPlaying
},
getCurrTrack(state) {
return state.curr_track
}
},
actions: {
}
})
export default store

Navigation guard keeps looping

I have a guard for my routes which does work in all aspects apart from when I wish to check a permissions object related to that page prior to continuing onto the url.
I have separated out the logic for the permissions check into a function and console logging it out all elements are working, in that it finds the right object in the array, finds the right key and value, and allows or blocks accordingly.
My problem though is that when I go through this route hitting this function it loops endlessly and crashes the browser. I think my overarching logic is fine but have I screwed up its implementation somewhere?
function guard (to, from, next) {
var loggedin_state = store.state.user.auth.loggedin // Boolean
var user = store.state.user.user // Array
var token = store.state.user.auth.token // String
var entryUrl // String
if(entryUrl == null || entryUrl == undefined){
entryUrl = to.path
}
if(loggedin_state == true) {
// Is the user profile blank
if(user == null) {
this.$store.dispatch('user/get_user_information', null)
}
// If they tried a route before logging in that would have been stored
if(entryUrl) {
// Store the url before wiping it
let url = entryUrl;
// Wipe the entry url variable
entryUrl = null;
// Carry on to permission checking function
return go_to_url(url);
} else {
// Go to stored url
return next(to.path)
}
} else {
// Is there a token assigned? If so they are approved and just need the profile information
if(token !== null) {
loggedin_state = true
this.$store.dispatch('user/get_user_information', null)
return go_to_url(to.path);
} else {
// Store entry url before redirect for use after login
entryUrl = to.path
// Re-route to login page
return next("/login");
}
}
function go_to_url(url) {
// Find matching object in user.permissions based upon url
var view_permissions = [
{ "area": "all", "read": 1, "create": 0, "edit": 0, "delete": 0 },
{ "area": "dashboard", "read": 1, "create": 0, "edit": 0, "delete": 0 }
];
// var view_permissions = store.state.user.permissions
var view_permission = view_permissions.find(view => view.area === to.name);
if(view_permission.read == 1) {
// Go to url
next(url);
} else {
// Re-route to somewhere
}
};
};
My problem was in passing a value to the next() function call. By removing that out it worked alright:
function guard (to, from, next) {
console.log('To:')
console.log(to)
console.log('From:')
console.log(from)
console.log('EntryUrl: ' + entryUrl)
// 1 - If no entry path was provided then set to
if(entryUrl == null || entryUrl == undefined){
entryUrl = to.path
console.log('EntryUrl: ' + entryUrl)
}
// 2 - Check if the user is marked as being logged in
var loggedin_state = store.state.user.auth.loggedin
if(loggedin_state == undefined) {
store.commit('user/set_delete_session', null)
return next("/login");
}
// 3 - If they are marked as logged in continue
var user = store.state.user.user
var token = store.state.user.auth.token
if(loggedin_state == true) {
// If the user isn't authorised with a token then send them to the log in page
if(token == null) {
store.commit('user/set_delete_session', null)
return next("/login");
}
// If they've got a token but no user profile data acquire it
if(user == null) {
UserApi.get_user_information(response.data.token)
.then(response => {
store.commit('user/set_user', response.data)
})
}
// If they tried a route before logging in that would have been stored
if(entryUrl) {
console.log('Go to saved URL')
// Store the url before wiping it
let url = entryUrl;
// Wipe the entry url variable
entryUrl = null;
// Go to stored url
return go_to_url(url);
} else {
console.log('Go to pointed url')
// Carry on to permission checking function
return go_to_url(to.path);
}
} else {
// The user is not logged in. Store the URL they were trying to visit and redirect them to the login page
entryUrl = to.path
console.log('EntryUrl: ' + entryUrl)
return next("/login");
}
function go_to_url(url) {
console.log(url)
// 1 - Grab the user permissions from the user profile
var permissions_array = null
if(user !== null) {
permissions_array = user.permissions
}
console.log(permissions_array)
// 2 - Check and route
if(permissions_array !== null) {
// Find the relevant permission object based upon the route name and the area key
var view_permissions = permissions_array.find(view => view.area === to.name);
console.log(view_permissions)
// If a permission object was found check its status, if no object found assume it is okay to view
if(view_permissions !== undefined) {
// If set to 1 the user can view this route, else reroute to a permissions denied page
if(view_permissions.read == 1) {
// Go to url
console.log('GUARD - PROCEED')
console.log(to.name)
next();
} else {
console.log('GUARD - BLOCKED')
return next("/permission-denied");
}
} else {
return next()
}
}
};
};

Get JavaScript Array of Objects to bind to .Net Core List of ViewModel

I have a JS Array of Objects which, at time of Post contains three variables per object:
ParticipantId,
Answer,
ScenarioId
During post, there is an Array the size of 8 (at current anyway) which all correctly contain data. When I call post request, the Controller does get hit as the breakpoint triggers, the issue is when I view the List<SurveyResponse> participantScenarios it is shown as having 0 values.
The thing I always struggle to understand is that magic communication and transform between JS and .Net so I am struggling to see where it is going wrong.
My JS Call:
postResponse: function () {
var data = JSON.stringify({ participantScenarios: this.scenarioResponses})
// POST /someUrl
this.$http.post('ScenariosVue/PostScenarioChoices', data).then(response => {
// success callback
}, response => {
// error callback
});
}
My .Net Core Controller
[HttpPost("PostScenarioChoices")]
public async Task<ActionResult> PostScenarioChoices(List<SurveyResponse> participantScenarios)
{
List<ParticipantScenarios> addParticipantScenarios = new List<ParticipantScenarios>();
foreach(var result in participantScenarios)
{
bool temp = false;
if(result.Answer == 1)
{
temp = true;
}
else if (result.Answer == 0)
{
temp = false;
}
else
{
return StatusCode(400);
}
addParticipantScenarios.Add(new ParticipantScenarios
{
ParticipantId = result.ParticipantId,
Answer = temp,
ScenarioId = result.ScenarioId
});
}
try
{
await _context.ParticipantScenarios.AddRangeAsync(addParticipantScenarios);
await _context.SaveChangesAsync();
return StatusCode(201);
}
catch
{
return StatusCode(400);
}
}

Adal.js not setting props in localStorage

I'm having a problem using the adal.js library without Angular. (I'm using Vue.js.)
I have an authentication context instance, which is constructed with the following options (exact values have been changed to protect the innocent):
let config = {
tenant: '<tenant id>',
clientId: '<client id>',
redirectUri: 'http://myapplication.com/index.html',
// popUp: true,
cacheLocation: 'localStorage'
}
On my login page, I call authContext.login(), which redirects me first to https://login.microsoftonline.com/, where I log into AAD. Upon successful login, another redirect takes me back to my application, at the URI I've configured above, along with an id_token parameter in the URL. However, no token or other properties are stored by the library in local storage, just a few properties that are the result of the configuration.
On successful login, All I've got in localStorage is
{
adal.access.token.key: "",
adal.error: ""
adal.error.description: ""
adal.expiration.key: "0"
adal.idtoken: ""
adal.login.error: ""
adal.login.request: "http://myapplication.com/#/login"
adal.nonce.idtoken: "<a non-empty string>"
adal.session.state: ""
adal.state.login: "<a non-empty string>"
adal.token.keys: ""
adal.username: ""
}
So, as far as AAD is concerned, I've successfully authenticated, but the library itself seems to have no notion of what user is logged in, what tokens are associated with them, when the token expires, etc. Any advice on how to proceed would be most appreciated. Thank you in advance for reading.
Active Directory Authentication Library for JavaScript (ADAL JS) helps you to use Azure AD for handling authentication in your single page applications. This library is optimized for working together with AngularJS.
It will not save the tokens into the cache unless we code it. You can check the relative code from adal-angular.js. Here is a piece of code for your reference:
The saveTokenFromHash method will also save the tokens into cache and this function will execute after the page redirect back to the Angular app.
adal.js:
AuthenticationContext.prototype.saveTokenFromHash = function (requestInfo) {
this._logstatus('State status:' + requestInfo.stateMatch);
this._saveItem(this.CONSTANTS.STORAGE.ERROR, '');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, '');
// Record error
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION)) {
this._logstatus('Error :' + requestInfo.parameters.error);
this._logstatus('Error description:' + requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
this._saveItem(this.CONSTANTS.STORAGE.FAILED_RENEW, requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
this._saveItem(this.CONSTANTS.STORAGE.ERROR, requestInfo.parameters.error);
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) {
this._loginInProgress = false;
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, requestInfo.parameters.errorDescription);
} else {
this._renewActive = false;
}
} else {
// It must verify the state from redirect
if (requestInfo.stateMatch) {
// record tokens to storage if exists
this._logstatus('State is right');
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.SESSION_STATE)) {
this._saveItem(this.CONSTANTS.STORAGE.SESSION_STATE, requestInfo.parameters[this.CONSTANTS.SESSION_STATE]);
}
var keys, resource;
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN)) {
this._logstatus('Fragment has access token');
// default resource
this._renewActive = false;
resource = this.config.loginResource;
if (!this._hasResource(resource)) {
keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS) || '';
this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, keys + resource + this.CONSTANTS.RESOURCE_DELIMETER);
}
if (requestInfo.requestType === this.REQUEST_TYPE.RENEW_TOKEN) {
resource = this._getResourceFromState(requestInfo.stateResponse);
}
// save token with related resource
this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, requestInfo.parameters[this.CONSTANTS.ACCESS_TOKEN]);
this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, this._expiresIn(requestInfo.parameters[this.CONSTANTS.EXPIRES_IN]));
}
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ID_TOKEN)) {
this._loginInProgress = false;
this._user = this._createUser(requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
if (this._user && this._user.profile) {
if (this._user.profile.nonce !== this._getItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN)) {
this._user = null;
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'Nonce is not same as ' + this._idTokenNonce);
} else {
this._saveItem(this.CONSTANTS.STORAGE.IDTOKEN, requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
// Save idtoken as access token for app itself
resource = this.config.clientId;
if (!this._hasResource(resource)) {
keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS) || '';
this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, keys + resource + this.CONSTANTS.RESOURCE_DELIMETER);
}
this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, this._user.profile.exp);
}
}
}
} else {
this._saveItem(this.CONSTANTS.STORAGE.ERROR, 'Invalid_state');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, 'Invalid_state');
if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) {
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'State is not same as ' + requestInfo.stateResponse);
}
}
}
};
And this function will be called in this.$get like below:
// special function that exposes methods in Angular controller
// $rootScope, $window, $q, $location, $timeout are injected by Angular
this.$get = ['$rootScope', '$window', '$q', '$location', '$timeout', function ($rootScope, $window, $q, $location, $timeout) {
var locationChangeHandler = function () {
var hash = $window.location.hash;
if (_adal.isCallback(hash)) {
// callback can come from login or iframe request
var requestInfo = _adal.getRequestInfo(hash);
_adal.saveTokenFromHash(requestInfo);
$window.location.hash = '';
if (requestInfo.requestType !== _adal.REQUEST_TYPE.LOGIN) {
_adal.callback = $window.parent.AuthenticationContext().callback;
}
// Return to callback if it is send from iframe
if (requestInfo.stateMatch) {
if (typeof _adal.callback === 'function') {
// Call within the same context without full page redirect keeps the callback
if (requestInfo.requestType === _adal.REQUEST_TYPE.RENEW_TOKEN) {
// Idtoken or Accestoken can be renewed
if (requestInfo.parameters['access_token']) {
_adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['access_token']);
return;
} else if (requestInfo.parameters['id_token']) {
_adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['id_token']);
return;
}
}
} else {
// normal full login redirect happened on the page
updateDataFromCache(_adal.config.loginResource);
if (_oauthData.userName) {
//IDtoken is added as token for the app
$timeout(function () {
updateDataFromCache(_adal.config.loginResource);
$rootScope.userInfo = _oauthData;
// redirect to login requested page
var loginStartPage = _adal._getItem(_adal.CONSTANTS.STORAGE.START_PAGE);
if (loginStartPage) {
$location.path(loginStartPage);
}
}, 1);
$rootScope.$broadcast('adal:loginSuccess');
} else {
$rootScope.$broadcast('adal:loginFailure', _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION));
}
}
}
} else {
// No callback. App resumes after closing or moving to new page.
// Check token and username
updateDataFromCache(_adal.config.loginResource);
if (!_adal._renewActive && !_oauthData.isAuthenticated && _oauthData.userName) {
if (!_adal._getItem(_adal.CONSTANTS.STORAGE.FAILED_RENEW)) {
// Idtoken is expired or not present
_adal.acquireToken(_adal.config.loginResource, function (error, tokenOut) {
if (error) {
$rootScope.$broadcast('adal:loginFailure', 'auto renew failure');
} else {
if (tokenOut) {
_oauthData.isAuthenticated = true;
}
}
});
}
}
}
$timeout(function () {
updateDataFromCache(_adal.config.loginResource);
$rootScope.userInfo = _oauthData;
}, 1);
}
...
And here is a sample code which could save the tokens into cache for your reference:
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<script src="node_modules\adal-angular\lib\adal.js"> </script>
<script src="config.js"> </script>
</head>
<body>
<div>
<button onclick="login()" >Login</button>
</div>
<script>
var authContext=new AuthenticationContext(config);
function login(){
authContext.login();
}
function init(configOptions){
if (configOptions) {
// redirect and logout_redirect are set to current location by default
var existingHash = window.location.hash;
var pathDefault = window.location.href;
if (existingHash) {
pathDefault = pathDefault.replace(existingHash, '');
}
configOptions.redirectUri = configOptions.redirectUri || pathDefault;
configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;
// create instance with given config
} else {
throw new Error('You must set configOptions, when calling init');
}
// loginresource is used to set authenticated status
updateDataFromCache(authContext.config.loginResource);
}
var _oauthData = { isAuthenticated: false, userName: '', loginError: '', profile: '' };
var updateDataFromCache = function (resource) {
// only cache lookup here to not interrupt with events
var token = authContext.getCachedToken(resource);
_oauthData.isAuthenticated = token !== null && token.length > 0;
var user = authContext.getCachedUser() || { userName: '' };
_oauthData.userName = user.userName;
_oauthData.profile = user.profile;
_oauthData.loginError = authContext.getLoginError();
};
init(config);
function saveTokenFromHash(){
var hash = window.location.hash;
var requestInfo = authContext.getRequestInfo(hash);
if (authContext.isCallback(hash)) {
// callback can come from login or iframe request
var requestInfo = authContext.getRequestInfo(hash);
authContext.saveTokenFromHash(requestInfo);
window.location.hash = '';
if (requestInfo.requestType !== authContext.REQUEST_TYPE.LOGIN) {
authContext.callback = window.parent.AuthenticationContext().callback;
}
}
}
saveTokenFromHash();
</script>
</body>
</html>

Pausing a game with ActionScript 2

I'm making a game where the player must avoid random falling objects. I dont know how to implement pausing. I've been stuck on this for 2 days!
I tried using gotoAndPlay and such, but the objects continue to run in the background. When I resume the game, they're still falling and it seems like the frame resets and loads new random falling objects.
var steps:Number = 10;
var spriteX:Number = 280;
var spriteY:Number = 650;
var alienCounter=1;
var asteroidCounter=1;
var live:Number=3;
var depthLevel=3000;
var score:Number = 0;
var gamePaused;
dropTimer=setInterval(createAlien,2000);
drpTimer2=setInterval(createAsteroid,1000);
//---- functions ----
function checkKeys()
{
if (Key.isDown(Key.RIGHT))
{
spriteX += steps;
}
else if (Key.isDown(Key.LEFT))
{
spriteX -= steps;
}
}
function updateSpaceship()
{
ship._x = spriteX;
ship._y = spriteY;
}
function createAlien()
{
var curr_alien;
curr_alien=attachMovie("alien","alien"+alienCounter,depthLevel);
curr_alien._y=40;
curr_alien._x=Math.random()*510+20;
curr_alien._xscale=curr_alien._yscale=50;
curr_alien.speed=Math.random()*10+3;
alienCounter+=1;
depthLevel+=1;
curr_alien.onEnterFrame=alienMove;
}
function alienMove()
{
if(!gamePaused)
{
this._y+=this.speed;
if(this.hitTest(ship))
{
score += 1;
trace(score);
removeMovieClip(this);
}
}
}
function createAsteroid()
{
var curr_asteroid;
curr_asteroid=attachMovie("asteroid","asteroid"+asteroidCounter,depthLevel);
curr_asteroid._y=40;
curr_asteroid._x=Math.random()*510+20;
curr_asteroid._xscale=curr_asteroid._yscale=50;
curr_asteroid.speed=Math.random()*10+3;
asteroidCounter+=1;
depthLevel+=1;
curr_asteroid.onEnterFrame=asteroidMove;
}
function asteroidMove()
{
if(!gamePaused)
{
this._y+=this.speed;
if(this.hitTest(ship))
{
live -= 1;
trace(live);
removeMovieClip(this);
if(live<=0)
{
gotoAndPlay(5);
}
}
}
}
this.onEnterFrame = function()
{
checkKeys();
updateSpaceship();
if(Key.isDown(80))
{
if(!gamePaused)
{
gamePaused=true;
gotoAndPlay(4);
}
else
{
gamePaused=false;
gotoAndStop(3);
}
}
};
i decided to use a key instead because i cannot find any solutions when trying to use a button. The pause function is not working as i expected, i need to enter key 'p' several times to pause it, but i dont want the frame resets and loads more random objects when i resume it.
try this:
remove your:
this.onEnterFrame = function()
{
checkKeys();
updateSpaceship();
if(Key.getCode() == 80)
{
if(!gamePaused)
{
gamePaused=true;
gotoAndPlay(4);
trace("AAA")
}
else
{
gamePaused=false;
gotoAndStop(3);
trace("BBB")
}
}
};
Add this (pause by pressing the 'P' key on your keyboard):
var keyListener:Object = new Object();
keyListener.onKeyUp = function() {
if(Key.getCode() == 80) {
gamePaused = !gamePaused;
mainLoop();
}
};
Key.addListener(keyListener);
function mainLoop() {
if (gamePaused) {
gotoAndStop(4); // update game actions here
trace("game is paused");
return;
}
gotoAndStop(3); // update game actions here
trace("game is running");
}
Alternatively if you need to pause using a button:
my_pause_Button.onRelease = function() { // your button instance name 'my_pause_Button'
gamePaused = !gamePaused;
mainLoop();
};
Put this in your button function or keydown function:
stage.frameRate = 0.01;