Createvector is undefined p5js - vector

UPDATE: Forgot to say, I'm using the p5.js editor. The rest of the sketch works, and loads the image.
When I run this code in the browser I get 'createVector is undefined'. According to the reference for p5.js I'm using the correct syntax.
Any ideas what is wrong?
var img;
var bg = 100;
var velocity = createVector(0,0);
var acceleration = createVector(0,0);
function setup() {
createCanvas(720, 400);
img = loadImage("assets/bb8body.png");
}
function keyPressed() {
if (keyIsPressed === true) {
if (key === 'd') {
acceleration++;
velocity.add(acceleration);
console.log(vx);
}
}
}
function damping(){
}
function draw() {
keyPressed();
background(bg);
image(img, velocity, 0);
damping();
}

I'm not 100% why, but createVector() works in setup() (not outside).
Additionally, I've spotted two small errors:
acceleration++;
This won't work as js doesn't support overloaded operators like c++, but you can use p5.Vector's add() function.
Also, the vx variable doesn't exist in the rest of your code.
Here's a modified version of your code using p5.Vector instances, but drawing a small box instead of the image, for testing purposes. You can run the demo bellow:
var img;
var bg = 100;
var velocity;// = createVector(0,0);
var acceleration;// = createVector(0,0);
function setup() {
createCanvas(720, 400);
velocity = createVector(0,0);
acceleration = createVector(0,0);
//img = loadImage("assets/bb8body.png");
}
function keyPressed() {
if (keyIsPressed === true) {
if (key === 'd') {
//acceleration++;
acceleration.add(1,1);
velocity.add(acceleration);
//console.log(vx);
console.log(velocity.x);
}
}
}
function damping(){
}
function draw() {
keyPressed();
background(bg);
rect(velocity.x,velocity.y,20,20)
//image(img, velocity, 0);
damping();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.22/p5.min.js"></script>

Related

HERE-SDK lite drag marker in MapView

I am just trying out the SDK Lite API and I am wondering how I can achieve to drag a MapMarker object from one place to another. I suggest, it works somehow with disabling the default onPan gesture, but actually the problem starts with picking an existing object.
Here is my code so far:
public void pickMarker(Point2D p) {
map.getGestures().disableDefaultAction(GestureType.PAN);
map.pickMapItems(p, 20f, pickMapItemsResult -> {
if (pickMapItemsResult != null) {
pickedMarker = pickMapItemsResult.getTopmostMarker();
} else {
map.getGestures().enableDefaultAction(GestureType.PAN);
}
});
}
public void dragMarker(Point2D p) {
if (pickedMarker != null) {
pickedMarker.setCoordinates(map.getCamera().viewToGeoCoordinates(p));
}
}
public boolean releaseMarker(Point2D p) {
map.getGestures().enableDefaultAction(GestureType.PAN);
if (pickedMarker != null) {
GeoCoordinates newCoordinates = map.getCamera().viewToGeoCoordinates(p);
pickedMarker.setCoordinates(newCoordinates);
pickedMarker = null;
return true;
}
return false;
}
while these functions are called on the three states of the onPanListener:
mapView.getGestures().setPanListener((gestureState, point2D, point2DUpdate, v) -> {
if (gestureState.equals(GestureState.BEGIN)) {
mapViewUIEngine.pickMarker(point2D);
}
if (gestureState.equals(GestureState.UPDATE)) {
mapViewUIEngine.dragMarker(point2DUpdate);
}
if (gestureState.equals(GestureState.END)) {
if (mapViewUIEngine.releaseMarker(point2DUpdate)) {
regionController.movePoint(0,
updateNewLocation(point2D, point2DUpdate);
}
}
});
From one of the developer in Github I now know, that the polygon is returned instead of the marker (which is lying on a polygon line, but how can I get the marker instead?
You can use map markers to precisely point to a location on the map.
The following method will add a custom map marker to the map:
MapImage mapImage = MapImageFactory.fromResource(context.getResources(), R.drawable.here_car);
MapMarker mapMarker = new MapMarker(geoCoordinates);
mapMarker.addImage(mapImage, new MapMarkerImageStyle());
mapView.getMapScene().addMapMarker(mapMarker);
For more details, please refer
https://developer.here.com/documentation/android-sdk/dev_guide/topics/map-items.html#add-map-markers

Select symbol definition path

I need to view the segments and handles of the path that defines a SymbolItem. It is a related issue to this one but in reverse (I want the behavior displayed on that jsfiddle).
As per the following example, I can view the bounding box of the SymbolItem, but I cannot select the path itself in order to view its segments/handles. What am I missing?
function onMouseDown(event) {
project.activeLayer.selected = false;
// Check whether there is something on that position already. If there isn't:
// Add a circle centered around the position of the mouse:
if (event.item === null) {
var circle = new Path.Circle(new Point(0, 0), 10);
circle.fillColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
var circleSymbol = new SymbolDefinition(circle);
multiply(circleSymbol, event.point);
}
// If there is an item at that position, select the item.
else {
event.item.selected = true;
}
}
function multiply(item, location) {
for (var i = 0; i < 10; i++) {
var next = item.place(location);
next.position.x = next.position.x + 20 * i;
}
}
Using SymbolDefinition/SymbolItem prevent you from changing properties of each symbol items.
The only thing you can do in this case is select all symbols which share a common definition.
To achieve what you want, you have to use Path directly.
Here is a sketch showing the solution.
function onMouseDown(event) {
project.activeLayer.selected = false;
if (event.item === null) {
var circle = new Path.Circle(new Point(0, 0), 10);
circle.fillColor = Color.random();
// just pass the circle instead of making a symbol definition
multiply(circle, event.point);
}
else {
event.item.selected = true;
}
}
function multiply(item, location) {
for (var i = 0; i < 10; i++) {
// use passed item for first iteration, then use a clone
var next = i === 0 ? item : item.clone();
next.position = location + [20 * i, 0];
}
}

Subpixel issues with an animated sprite in odd zoom levels of Safari and FF

I have the following fiddle which distills an issue I am having with a larger project
http://jsfiddle.net/zhaocnus/6N3v8/
in Firefox and Safari, this animation will start having a jittering effect left and right on odd zoom levels (zoom in/out using Ctrl+/- or Cmd+/- on Mac). I believe this is do to sub-pixel rendering issues and the differences between the various browsers round up or down pixels during the zoom calculations, but I have no idea how to fix it and am looking for any suggestions.
I can't use more modern CSS3 animation features as I need to support legacy browsers like IE7.
(code from fiddle below, can't seem to post without it, although not sure it makes sense without CSS and HTML)
// js spritemap animation
// constants
var COUNTER_MAX = 9,
OFFSET = -50,
FRAMERATE = 100;
// variables
var _counter = 0,
_animElm = document.getElementById('animation'),
_supportBgPosX = false;
// functions
function play() {
// update counter
_counter++;
if (_counter > COUNTER_MAX) {
_counter = 0;
}
// show current frame
if (_supportBgPosX) {
_animElm.style.backgroundPositionX = (_counter * OFFSET) + 'px';
} else {
_animElm.style.backgroundPosition = (_counter * OFFSET) + 'px 0';
}
// next frame
setTimeout(play, FRAMERATE);
}
// check if browser support backgroundPositionX
if (_animElm.style.backgroundPositionX != undefined) {
_supportBgPosX = true;
}
// start animation
play();
Instead of moving the background to the new frame, have a canvas tag re-draw the frame. The canvas tag handles sub-pixel interpretation independent of the browser and because of this you not only control the render (browser agnostic) but also solve the jitter issue as it's being re-drawn frame-by-frame into the canvas' dimensions in realtime.
Zooming is specifically tough because there's no reliable way to detect the zoom level from the browser using jQuery or plain-ole javascript.
Check out the demo here: http://jsfiddle.net/zhaocnus/Gr9TF/
*Credit goes to my coworker zhaocnus for the solution. I'm simply answering this question on his behalf.
// js spritemap animation
// constants
var COUNTER_MAX = 14,
OFFSET = -200,
FRAMERATE = 100;
// variables
var _counter = 0,
_sprite = document.getElementById("sprite"),
_canvas = document.getElementById("anim-canvas"),
_ctx = _canvas.getContext("2d"),
_img = null;
// functions
function play() {
// update counter
_counter++;
if (_counter > COUNTER_MAX) {
_counter = 0;
}
// show current frame
_ctx.clearRect(0, 0, _canvas.width, _canvas.height);
_ctx.drawImage(_img, _counter * OFFSET, 0);
// next frame
setTimeout(play, FRAMERATE);
}
function getStyle(oElm, strCssRule) {
var strValue = '';
if (document.defaultView && document.defaultView.getComputedStyle) {
strValue = document.defaultView.getComputedStyle(oElm, null).getPropertyValue(strCssRule);
} else if (oElm.currentStyle) {
var strCssRule = strCssRule.replace(_styleRegExp, function (strMatch, p1) {
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return String(strValue);
}
function initCanvas(callback) {
var url = getStyle(_sprite, 'background-image');
url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
_img = new Image();
_img.onload = function(){
_ctx.drawImage(_img, 0, 0);
callback();
};
_img.src = url;
}
// start animation
initCanvas(play);

creating a Placemarks that can be hidden

I have been trying to create a Placemark that I can hide and show (like turning visibility on and off) on demand (on click)... I am using this to make the placemark:
function placemark(lat, long, name, url, iconsrc){
var placemark = ge.createPlacemark(name);
ge.getFeatures().appendChild(placemark);
placemark.setName(name);
// Create style map for placemark
var icon = ge.createIcon('');
if(iconsrc == "0")
icon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
else{
icon.setHref(iconsrc);
}
var style = ge.createStyle('');
style.getIconStyle().setIcon(icon);
if(iconsrc != "0")
style.getIconStyle().setScale(2.5);
placemark.setStyleSelector(style);
// Create point
var point = ge.createPoint('');
point.setLatitude(lat);
point.setLongitude(long);
//point.setAltitudeMode(1500);
placemark.setGeometry(point);
google.earth.addEventListener(placemark, 'click', function(event) {
// Prevent the default balloon from popping up.
event.preventDefault();
var balloon = ge.createHtmlStringBalloon('');
balloon.setFeature(placemark); // optional
balloon.setContentString(
'<iframe src="'+ url +'" frameborder="0"></iframe>');
ge.setBalloon(balloon);
});
}
I have tried everything... from this:
function hidePlacemark(name){
var children = ge.getFeatures().getChildNodes();
for(var i = 0; i < children.getLength(); i++) {
var child = children.item(i);
if(child.getType() == 'KmlPlacemark') {
if(child.getId()== name)
child.setVisibility(false);
}
}
}
to using this ge.getFeatures().removeChild(child);
can anyone point me to the right direction on creating a function that will allow me to turn the visibility on/off on demand please.
Your hidePlacemark function is missing some {} in your final IF statement
if(child.getId()== name)
you have
function hidePlacemark(name){
var children = ge.getFeatures().getChildNodes();
for(var i = 0; i < children.getLength(); i++) {
var child = children.item(i);
if(child.getType() == 'KmlPlacemark') {
if(child.getId()== name)
child.setVisibility(false);
}
}
}
make it
function hidePlacemark(name){
var children = ge.getFeatures().getChildNodes();
for(var i = 0; i < children.getLength(); i++) {
var child = children.item(i);
if(child.getType() == 'KmlPlacemark') {
if(child.getId()== name) {
child.setVisibility(false);
}
}
}
}
HOWEVER ------- you are better off doing this as it is much faster as you don't need to loop through ALL your placemarks
function hidePlacemark(name) {
var placemark = ge.getElementById(name);
placemark.setVisibility(false);
}
I think the plain ge.getFeatures().removeChild(placemark); works.
I played with this GooglePlayground, and just added the following code to line 8 (that is empty in this GooglePlayground Sample):
addSampleButton('Hide Placemark', function(){
ge.getFeatures().removeChild(placemark);
});
Clicking the button Hide Placemark hides the placemark like a charm here. Any chances your problem is somewhere else in your code?

Flash "visible" issue

I'm writing a tool in Flex that lets me design composite sprites using layered bitmaps and then "bake" them into a low overhead single bitmapData. I've discovered a strange behavior I can't explain: toggling the "visible" property of my layers works twice for each layer (i.e., I can turn it off, then on again) and then never again for that layer-- the layer stays visible from that point on.
If I override "set visible" on the layer as such:
override public function set visible(value:Boolean):void
{
if(value == false) this.alpha = 0;
else {this.alpha = 1;}
}
The problem goes away and I can toggle "visibility" as much as I want. Any ideas what might be causing this?
Edit:
Here is the code that makes the call:
private function onVisibleChange():void
{
_layer.visible = layerVisible.selected;
changed();
}
The changed() method "bakes" the bitmap:
public function getBaked():BitmapData
{
var w:int = _composite.width + (_atmosphereOuterBlur * 2);
var h:int = _composite.height + (_atmosphereOuterBlur * 2);
var bmpData:BitmapData = new BitmapData(w,h,true,0x00000000);
var matrix:Matrix = new Matrix();
var bounds:Rectangle = this.getBounds(this);
matrix.translate(w/2,h/2);
bmpData.draw(this,matrix,null,null,new Rectangle(0,0,w,h),true);
return bmpData;
}
Incidentally, while the layer is still visible, using the Flex debugger I can verify that the layer's visible value is "false".
Wait a frame between setting visible and calling changed(). Use the invalidateProperties()/commitProperties() model.
private bool _isChanged = false;
private function onVisibleChange():void
{
_layer.visible = layerVisible.selected;
_isChanged = true;
invalidateProperties();
}
protected override function commitProperties():void {
super.commitProperties();
if (_isChanged) {
_isChanged = false;
changed();
}
}

Resources