Swapping variable in p5.js - processing

I have defined a variable called fighter in my program. I have an if keyPressed function which selects a specific image based on key. The problem I am having is that that images are swapping but overlapping the original image. I also attempted to add an else statement with the fighter in the original position but still same response.
var fighter;
var stance;
var kick;
var jab;
var cross;
var mx; //Use to constrain fighter to center of circle
var my;
function preload(){
stance = loadImage("img/stance.svg");
kick = loadImage("img/kick.svg");
jab = loadImage("img/jab.svg");
cross = loadImage("img/cross.svg");
};
function setup(){
createCanvas(1280,720);
};
function draw(){
background(0, 246, 255);
fill("red");
ellipse(width/2,height/2,500,500);
mx = constrain(mouseX,width/2-250,width/2+250);
my = constrain(mouseY,height/2-250,height/2+250);
fighter = image(stance,mx,my);
if(keyIsPressed){
if((key == "a" || key == "A")){
fighter = "";
fighter = image(jab,mx,my);
}
else if ((key == "w" || key == "W")) {
fighter = image(cross,mx,my);
}
else if ((key == "s" || key == "S")) {
fighter = image(kick,mx,my);
}
};
};

You're setting fighter equal to the value returned by the image() function for some reason. This doesn't make a ton of sense.
Instead, I think you want to set fighter equal to one of the images, and then pass fighter into the image() function. Something like this:
fighter = stance;
if(keyIsPressed){
if((key == "a" || key == "A")){
fighter = jab;
}
else if ((key == "w" || key == "W")) {
fighter = cross
}
else if ((key == "s" || key == "S")) {
fighter = kick;
}
}
image(fighter, mx,my);

Related

Is there a way I can make my script more efficient?

I have created the below script to add a timestamp when a cell equals a specific value. This script repeats for each row but it is not efficient. How can I make this simpler and quicker? Below is an extract of the script, it repeats for each row
function MyFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('Overview')
var cell = sheet.getRange('H3').getValue()
var sent = sheet.getRange('p3').getValue()
if (cell == "Full" && sent == "") {
sheet.getRange('p3').setValue(new Date())
}
else if (cell == "Open" && sent == "") {
sheet.getRange('p3').setValue("")
}
}
Try this.
function MyFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Overview');
// get range H3:P were H=8, P=16, 9 columns total or index 0 to 8
var data = sheet.getRange(3,8,sheet.getLastRow()-2,9).getValues(); // get range H3:P
var i = 0;
var row = null;
for( i=0; i<data.length; i++ ) {
row = data[i];
if( ( row[0] === "Full" ) && ( row[8] === "" ) ) {
row[8] = new Date();
}
// Your else doesn't do anything if blank set blank ??
row.splice(0,8); // extract only column P
}
sheet.getRange(3,16,data.length,1).setValues(data);
}
Try using setvalues() method of class range
function MyFunction() {
const ss = SpreadsheetApp.getActive()
const sh = ss.getSheetByName('Overview');
const rg = sh.getDataRange();
const vs = rg.getValues();
let vo = vs.map(r => {
if( r[7] == "Full") r[15]=new Date()
if( r[7] == "Open") r[15]='';
return [r[15]];
});
sh.getRange(2,16,vo.length,1).setValues(vo);
}

Is it possible to round the edges of a row in jetpack?

This is what I'm trying to achieve:
So I have created 2 rounded buttons in a row and gave different background colors depending whether they're selected or not. The goal is to create a kind of an illusion of a tab/toggle.
The unselected button will have the same color as the row's background color. Unfortunately, since a row is a rectangle shape there comes a residue space at the corners that still shows the background color .
This is my code for the buttons
val cornerRadius = 20.dp
var selectedIndex by remember { mutableStateOf(0)}
val configuration = LocalConfiguration.current
val screenWidth = configuration.screenWidthDp.dp
val items = listOf(
OutlinedButton(onClick = { /*TODO*/ }) {
},
OutlinedButton(onClick = { /*TODO*/ }) {
})
Row(
modifier = Modifier
.padding(top = 8.dp)
.wrapContentHeight()
.width(screenWidth).background(color = Color.Gray).clip(shape = RoundedCornerShape(20.dp))
) {
// Spacer(modifier = Modifier.weight(1f))
items.forEachIndexed { index, item ->
OutlinedButton(modifier = Modifier
.wrapContentHeight()
.width(screenWidth/2),
shape = when (index) {
// left outer button
0 -> (if (selectedIndex == index) {
RoundedCornerShape(
topStart = cornerRadius,
topEnd = cornerRadius,
bottomStart = cornerRadius,
bottomEnd = cornerRadius
)
} else {
RoundedCornerShape(
topStart = cornerRadius,
topEnd = cornerRadius,
bottomStart = cornerRadius,
bottomEnd = cornerRadius
)
})
//rightouterbutton
else -> (if (selectedIndex == index) {
RoundedCornerShape(
topStart = cornerRadius,
topEnd = cornerRadius,
bottomStart = cornerRadius,
bottomEnd = cornerRadius
)
}
else{RoundedCornerShape(
topStart = 0.dp,
topEnd = cornerRadius,
bottomStart = 0.dp,
bottomEnd = cornerRadius
)})
},
border = BorderStroke(
1.dp, if (selectedIndex == index) {
Color.Transparent
} else {
Color.Transparent
}
),
colors = if (selectedIndex == index) {
// colors when selected
ButtonDefaults.outlinedButtonColors(
backgroundColor = Color.Yellow,
contentColor = Color.Black
)
} else {
// colors when not selected
ButtonDefaults.outlinedButtonColors(
backgroundColor = Color.Gray,
contentColor = Color.Black
)
},
onClick = { selectedIndex = index },
) {
if (index == 0) {
Text(
text = "In progress",
color = if (selectedIndex == index) {
Color.Black
} else {
Color.DarkGray.copy(alpha = 0.9f)
},
modifier = Modifier.padding(horizontal = 8.dp)
)
} else {
Text(
text = "Completed",
color = if (selectedIndex == index) {
MaterialTheme.colors.primary
} else {
Color.DarkGray.copy(alpha = 0.9f)
},
modifier = Modifier.padding(horizontal = 8.dp)
)
}
}
}
}
Modifier.clip applied after the Modifier.background has no effect in your case, you need to reverse the order. Read more about why the order of modifiers matters in this answer
.clip(shape = RoundedCornerShape(20.dp))
.background(color = Color.Gray)
Another option in the case of Modifier.background is that you can apply the shape specifically to the background color. Note that this solution will not clip other view content to the shape as Modifier.clip does, but in your case it fits.
.background(color = Color.Gray, shape = RoundedCornerShape(20.dp))

3d-force-graph node and sprite text

I'm using the react version of 3d-force-graph and making some default nodes (spheres) and some sprite text nodes. (Return false does the default sphere node)
nodeThreeObject={node => {
if (node.id % 6 == 0){
const sprite = new SpriteText(buzzwords[node.id % buzzwords.length]);
sprite.color = "#8898aa";
sprite.textHeight = 12;
return sprite;
} else {
return false
}
}}
I was wondering how I could add a sphere node behind my text nodes. They look a little off without it.
simply set nodeThreeObjectExtend to true:
<ForceGraph3D
graphData={graphData}
nodeThreeObjectExtend={true}
nodeThreeObject={node => {
if (node.id % 6 == 0){
const sprite = new SpriteText(buzzwords[node.id % buzzwords.length]);
sprite.color = "#8898aa";
sprite.textHeight = 12;
return sprite;
} else {
return false
}
}}

Ace Editor: Lock or Readonly Code Segment

Using the Ace Code Editor can I lock or make readonly a segment of code but still allow other lines of code to be written or edited during a session?
Here is the start of a solution:
$(function() {
var editor = ace.edit("editor1")
, session = editor.getSession()
, Range = require("ace/range").Range
, range = new Range(1, 4, 1, 10)
, markerId = session.addMarker(range, "readonly-highlight");
session.setMode("ace/mode/javascript");
editor.keyBinding.addKeyboardHandler({
handleKeyboard : function(data, hash, keyString, keyCode, event) {
if (hash === -1 || (keyCode <= 40 && keyCode >= 37)) return false;
if (intersects(range)) {
return {command:"null", passEvent:false};
}
}
});
before(editor, 'onPaste', preventReadonly);
before(editor, 'onCut', preventReadonly);
range.start = session.doc.createAnchor(range.start);
range.end = session.doc.createAnchor(range.end);
range.end.$insertRight = true;
function before(obj, method, wrapper) {
var orig = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
return wrapper.call(this, function(){
return orig.apply(obj, args);
}, args);
}
return obj[method];
}
function intersects(range) {
return editor.getSelectionRange().intersects(range);
}
function preventReadonly(next, args) {
if (intersects(range)) return;
next();
}
});
see it working in this fiddle: http://jsfiddle.net/bzwheeler/btsxgena/
The major working pieces are:
create start and end ace anchors which track the location of a 'readonly' portion as the document around it changes.
create a range to encapsulate the anchors
add a custom keyhandler to check if the current impending keypress will affect the readonly range and cancel it if so.
add custom paste/cut handlers to protect against right-click menu and browser menu cut/paste actions
You can do it by listening to the exec events:
// Prevent editing first and last line of editor
editor.commands.on("exec", function(e) {
var rowCol = editor.selection.getCursor();
if ((rowCol.row === 0) || ((rowCol.row + 1) === editor.session.getLength())) {
e.preventDefault();
e.stopPropagation();
}
});
Source: https://jsfiddle.net/tripflex/y0huvc1b/
I suggest something else easier and more reliable to prevent range to be modified (check it!)
var old$tryReplace = editor.$tryReplace;
editor.$tryReplace = function(range, replacement) {
return intersects(range)?null:old$tryReplace.apply(this, arguments);
}
var session = editor.getSession();
var oldInsert = session.insert;
session.insert = function(position, text) {
return oldInsert.apply(this, [position, outsideRange(position)?text:""]);
}
var oldRemove = session.remove;
session.remove = function(range) {
return intersects(range)?false:oldRemove.apply(this, arguments);
}
var oldMoveText = session.moveText;
session.moveText = function(fromRange, toPosition, copy) {
if (intersects(fromRange) || !outsideRange(toPosition)) return fromRange;
return oldMoveText.apply(this, arguments)
}
outsideRange = function (position) {
var s0 = range.start;
if (position.row < s0.row || (position.row == s0.row && position.column <= s0.column)) return true; // position must be before range.start
var e0 = range.end;
if (position.row > e0.row || (position.row == e0.row && position.column >= e0.column)) return true; // or after range.end
return false;
}
intersects = function(withRange) {
var e = withRange.end, s0 = range.start, s = withRange.start, e0 = range.end;
if (e.row < s0.row || (e.row == s0.row && e.column <= s0.column)) return false; // withRange.end must be before range.start
if (s.row > e0.row || (s.row == e0.row && s.column >= e0.column)) return false; // or withRange.start must be after range.end
return true;
}

How to know which body collide?

i am using cocos2d and box2d, with contact listener, and lets say i have a body that can hit a number of other bodies, BUT each one of them is turn on the contact listener.
so how can i know who hit who ?
i have this in my tick :
for(pos = _contactListener->_contacts.begin(); pos != _contactListener->_contacts.end(); ++pos)
{
MyContact contact = *pos;
b2Body *bodyA=contact.fixtureA->GetBody();
b2Body *bodyB=contact.fixtureB->GetBody();
//check if collision between to bodies
if( bodyA->GetUserData() !=NULL && bodyB->GetUserData() !=NULL) //if ((contact.fixtureA == _bottomFixture && contact.fixtureB == _ballFixture) ||(contact.fixtureA == _ballFixture && contact.fixtureB == _bottomFixture))
{
NSLog(#"Ball hit bottom!");
}
thanks a lot .
while creating the body set userdata like this
CCSprite *red=[CCSprite spriteWithFile:#"red.png"];
red.tag=3;
[self addChild:red];
b2BodyDef bd;
bd.type=b2_dynamicBody;
bd.position.Set(w/PTM_RATIO,h/PTM_RATIO);
bd.userData=red;
for(pos = _contactListener->_contacts.begin(); pos != _contactListener->_contacts.end(); ++pos)
{
MyContact contact = *pos;
b2Body *bodyA=contact.fixtureA->GetBody();
b2Body *bodyB=contact.fixtureB->GetBody();
//check if collision between to bodies
if( bodyA->GetUserData() !=NULL && bodyB->GetUserData() !=NULL) //if ((contact.fixtureA == _bottomFixture && contact.fixtureB == _ballFixture) ||(contact.fixtureA == _ballFixture && contact.fixtureB == _bottomFixture))
{
so here
CCSprite *actor = (CCSprite*)bodyA->GetUserData();
if ([actor tag] == 3) {
//red box
}
}
Put some identifier into user data. For example:
struct MyUserData
{
int myUniqueId;
};
When creating bodies attach some unique number to each and then you will be able to understand which body was colliding.

Resources