PHASER - Access var of obj inside of group - phaser-framework

I have a group of objects and I want to access the object that is being touched (using game.physics.arcade.overlap) as I need to access one of its variables. Could anyone point me out any suggestions? Thanks in advance.

You did not specify the type of physics but I assume it's Arcade:
function create()
{
...
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
veggies = game.add.group();
veggies.enableBody = true;
veggies.physicsBodyType = Phaser.Physics.ARCADE;
...
//Create veggies, bullets, etc...
}
function update()
{
...
game.physics.arcade.overlap(bullets, veggies, collision, null, this);
...
}
function collision(bullet, veg)
{
console.log(bullet);
console.log(veg);
}
The "collision" function captures the group elements when the event occurs, you can use it for "sprite vs group" or "group vs group" (with ARCADE physics)

Related

Prevent nested lists in text-editor (froala)

I need to prevent/disable nested lists in text editor implemented in Angular. So far i wrote a hack that undos a nested list when created by the user. But if the user creates a normal list and presses the tab-key the list is shown as nested for a few milliseconds until my hack sets in back to a normal list. I need something like event.preventDefault() or stopPropagation() on tab-event keydown but unfortunately that event is not tracked for some reason. Also the froala settings with tabSpaces: falseis not showing any difference when it comes to nested list...in summary i want is: if the user creates a list and presses the tab-key that nothing happens, not even for a millisecond. Has anyone an idea about that?
Froala’s support told us, there’s no built-in way to suppress nested list creation. They result from TAB key getting hit with the caret on a list item. However we found a way to get around this using MutationObserver
Basically we move the now nested list item to his former sibling and remove the newly created list. Finally we take care of the caret position.
var observer = new MutationObserver(mutationObserverCallback);
observer.observe(editorNode, {
childList: true,
subtree: true
});
var mutationObserverCallback = function (mutationList) {
var setCaret = function (ele) {
if (ele.nextSibling) {
ele = ele.nextSibling;
}
var range = document.createRange();
var sel = window.getSelection();
range.setStart(ele, 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
};
var handleAddedListNode = function (listNode) {
if (! listNode.parentNode) {
return;
}
var parentListItem = listNode.parentNode.closest('li');
if (!parentListItem) {
return;
}
var idx = listNode.children.length - 1;
while (idx >= 0) {
var childNode = listNode.children[idx];
if (parentListItem.nextSibling) {
parentListItem.parentNode.insertBefore(childNode, parentListItem.nextSibling);
} else {
parentListItem.parentNode.appendChild(childNode);
}
--idx;
}
setCaret(parentListItem);
listNode.parentNode.removeChild(listNode);
};
mutationList.forEach(function (mutation) {
var addedNodes = mutation.addedNodes;
if (!addedNodes.length) {
return;
}
for (var i = 0; i < addedNodes.length; i++) {
var currentNode = addedNodes[i];
switch (currentNode.nodeName.toLowerCase()) {
case 'ol':
case 'ul':
handleAddedListNode(currentNode);
break;
// more optimizations
}
}
})
};

tableView didSelectRowAt indexPath not firing the first time the view loads, works great the second time

I have a tableView in a View Controller with delegate and datasource wired up through the IB. I'm using the tableView for multi selection. In my didSelectRowAt IndexPath, selection lets the user mark a relationship between two Core Data entities:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let wageClassObject = self.wageClasses[indexPath.row]
let wageClassStatus = wageClassObject.value(forKey: "checked") as? Bool
wageClassObject.setValue(!wageClassStatus!, forKey:"checked")
if (wageClassStatus)! {
proposalToEdit?.addToWageClasses(wageClassObject)
}
else {
proposalToEdit?.removeFromWageClasses(wageClassObject)
}
}
When the user loads the view the first time, selecting a row has no effect. When the user loads the view the second time, the add and remove functions work great.
I've tried every solution suggested in this thread but no dice. I can't find a case quite like mine, either, where the issue is that it doesn't work the first time the view loads.
Suggestions greatly appreciated!
Edited to add: viewDidLoad and Core Data code
override func viewDidLoad() {
loadProposalData()
tableView.reloadData()
super.viewDidLoad()
proposalNameField.delegate = self
pensionField.delegate = self
percentField.delegate = self
if let topItem = self.navigationController?.navigationBar.topItem {
topItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
}
if wageClasses != nil {
getWageClasses()
print("\(wageClasses)")
}
}
func getWageClasses(){
let fetchRequest: NSFetchRequest<WageClass> = WageClass.fetchRequest()
do {
try self.wageClasses = context.fetch(fetchRequest)
} catch {
// handle error
}
}
#IBAction func calculateButtonTapped(_ sender: UIButton) {
var proposal: Proposal!
if proposalToEdit == nil {
proposal = Proposal(context: context)
} else {
proposal = proposalToEdit
}
proposal.dateCreated = currentDateTime as NSDate?
if let proposalName = proposalNameField.text {
proposal.proposalName = proposalName
}
if let pensionContribution = pensionField.text {
proposal.pensionContribution = (pensionContribution as NSString).doubleValue
}
if let percentIncrease = percentField.text {
proposal.percentIncrease = (percentIncrease as NSString).doubleValue
}
/// if let setting the checked value?
adD.saveContext()
_ = navigationController?.popViewController(animated: true)
}
I am not using viewDidAppear.
A little more about the Core Data. I have two entities, proposal and wageClass. Both have a to-many relationship to each other. On this viewController, the user can edit the proposal through three textfields (name, percent increase, pension amount) and then select related wageClasses from the tableView.
I want the user to be able to input the proposal fields and select the related wageClasses the first time they click the Add button in the nav bar on the previous viewController. What's happening is that the user clicks add, inputs the data to the text fields, selects the wage classes, and hits calculate. The text fields save and the labels update with the programmed calculations, but the wageClasses data remain nil. If the user selects the proposal again (that's what I mean by loads the view a second time above) then the user can add the wageClasses and all the calculations run correctly. But not before that second opening of the view.
screenshot of the view
You code uses proposalToEdit instance variable:
if (wageClassStatus)! {
proposalToEdit?.addToWageClasses(wageClassObject)
}
else {
proposalToEdit?.removeFromWageClasses(wageClassObject)
}
Which is basically nil here, it must be initialized before calling this functions, thus making this calls not executed (can't be done on nil object). You insert it to the context for the first time in calculateButtonTapped:
if proposalToEdit == nil {
proposal = Proposal(context: context)
}
if you want it to work first time (i.e. before first click on 'calculate'), add above code somewhere in viewDidLoad, like this:
override func viewDidLoad() {
loadProposalData()
if proposalToEdit == nil {
proposal = Proposal(context: context)
}
If above doesn't work I suggest you add a link to the repository to help debug this code, I cannot find more flaws in here, but there are no details in add and remove implementations, as well as how your core data stack works.
If anyone is stuck on the same problem, the key is to create the core data object before you add a relationship to another object. The above code doesn't work because I was trying to add relationships to objects that didn't yet exist.
My solution was to separate the operations in two view controllers but I would love to know more about how such can be achieved in one view controller.

JavaFX2 TreeView menu create

I have a Treeview with menu content, which is working. I am just not sure how can I implement more root menu to add?
Because this code only shows the "File" menu and all of submenus, but not the other roots.
-Also I would like to ask how could I make these submenus to act like links and create mouselisteners to them? Where is the right place to take the listeners?
The code is the following:
TreeItem<String> treeItemRoot1 = new TreeItem<> ("File");
TreeItem<String> treeItemRoot2 = new TreeItem<> ("Edit");
TreeItem<String> treeItemRoot3 = new TreeItem<> ("View");
TreeItem<String> treeItemRoot4 = new TreeItem<> ("Tools");
TreeItem<String> treeItemRoot5 = new TreeItem<> ("Help");
TreeItem<String> nodeItemA = new TreeItem<>("Item A");
TreeItem<String> nodeItemB = new TreeItem<>("Item B");
TreeItem<String> nodeItemC = new TreeItem<>("Item C");
treeItemRoot1.getChildren().addAll(nodeItemA, nodeItemB, nodeItemC);
TreeView<String> treeView = new TreeView<>(treeItemRoot1);
StackPane.getChildren().add(treeView);
The first part of your question is answered here: Set two root nodes for TreeView
For the second part, it depends on exactly what functionality you want. If you want to respond to a change in the selected item in the tree (this would include the user selecting either with the mouse or by using the keyboard), so can add a listener to the tree's selected item:
treeView.getSelectionModel().selectedItemProperty().addListener((obs, oldItem, newItem) -> {
if (newItem == treeItemRoot1) {
// "file" selected...
} else if (newItem == treeItemRoot2) {
// edit selected
} // etc...
});
If you genuinely want a mouse listener, you need to add a listener to the cell. To do this, use a cell factory:
treeView.setCellFactory(tv -> {
TreeCell<String> cell = new TreeCell<>();
cell.textProperty().bind(cell.itemProperty());
cell.setOnMousePressed(event -> {
TreeItem<String> item = cell.getTreeItem();
if (item == treeItemRoot1) {
// "file" clicked...
} else if (item == treeItemRoot2) {
// etc...
}
}
return cell ;
});
You can probably find ways to organize the code a little more cleanly, and avoid the big if-else construct in either case.

How to change variable name inside loop dynamically in C#?

I have foreach loop to listView control, I want to create objects for every listView content, so i want to change the name of the object incrementally by foreach loop
foreach (var item in listViewStates.Items)
{
State s = new State
{
ID = MaxStateID,
Name = listViewStates.Items[0].Text,
WorkflowID = MaxWFID,
DueDate = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[1].Text),
Priority = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[2].Text),
RoleID = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[3].Text),
Status =Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[4].Text)
};
i++;
}
the variable is s from the State Class
You might have the wrong approach. What you need to do with your state object is add it to a collection, and work it from there. It's much easier to track this way.
Example with a local list for use after the loop, in the function:
public void MyFunction()
{
List<State> states = new List<State>();
foreach (var item in listViewStates.Items)
{
State s = new State
{
//Set state properties
};
states.Add(s);
}
//Use your states here, address with brackets
//states[0].ID ...
}
Example with a class-level list for later use outside the function:
List<State> _states;
public void MyFunction()
{
_states = new List<State>();
foreach (var item in listViewStates.Items)
{
State s = new State
{
//Set state properties
};
_states.Add(s);
}
//Now, after calling the function, your states remain
//You can address them the same way as above, with brackets
//_states[0].ID ...
}

MonoTouch Dialog elements are not updating/repainting themselves

I have the following in a Section:
_favElement = new StyledStringElement (string.Empty);
_favElement.Alignment = UITextAlignment.Center;
if (_room.IsFavourite) {
_favElement.Image = UIImage.FromBundle ("Images/thumbs_up.png");
_favElement.Caption = "Unmark as Favourite";
} else {
_favElement.Image = null;
_favElement.Caption = "Mark as Favourite";
}
_favElement.Tapped += favElement_Tapped;
Then when I press the element I want the following to happen:
private void favElement_Tapped ()
{
if (_room.IsFavourite) {
_favElement.Image = null;
_favElement.Caption = "Mark as Favourite";
} else {
_favElement.Image = UIImage.FromBundle ("Images/thumbs_up.png");
_favElement.Caption = "Unmark as Favourite";
}
_room.IsFavourite = !_room.IsFavourite;
}
However the image and text does not change in the actual element when the element is tapped. Is there a refresh method or something that must be called? I've also tried changing the Accessory on Tapped as well and nothing changes. The properties behind do reflect the correct values though.
An alternative to reloading the UITableView is to reload the Element using code like this (copied from Touch.Unit):
if (GetContainerTableView () != null) {
var root = GetImmediateRootElement ();
root.Reload (this, UITableViewRowAnimation.Fade);
}
assuming that your code is in DialogViewController,add this
this.ReloadData();
but in your case I recommend you to use BooleanImageElement

Resources