I have done some python in the shell and I though this part of python I could get by with easily. . . But the Blender Module hates me. How do I use the math functions correctly? Simply doing:
I have the health property printing debug. The arithmetic one either doen’t work, or it won’t update the object’s property in the debug. When I assign the property it updates just fine.
When programming variables should not change unless they are explicitly told to do so. As such a variable can only be changed with an = operator. There are a few exceptions to this rule but I can’t think of any to worry about in the BGE.
The operation you wrote does the arithmetic but doesn’t put it anywhere. The code for the operation you want is:
owner[‘health’] = owner[‘health’] - 1
Due to the redundancy in the code most programming languages support a shorthand version of this:
owner[‘health’] -= 1
This is basic programming not specific to the BGE. I would recommend that you find and read a good python tutorial as it will make everything a lot easier.
Think about it.
-= is the decrement operator. It’s shorthand for
variable = variable - factor
Why is this necessary? Well, you asked about maths functions, so lets take a look at traditional algebra;
A = 2x + 4
B = A - 2x
By your example, setting B to A - 2x would in fact end up subtracting 2x from A.
10 - 2
Equals eight, but we haven’t said what that signifies. In maths (and Python) we have to state what a value means to us somewhere on one side of an equals sign (or function notation).
Hence, += value (or value = value + other_value) is the solution. This is the reason nearly all programming languages have such operators, with C++ having the ++ and – operators.
“owner[‘health’] - 1” does not and should not change the value of ‘health’. It is a mathematical expression that returns a numeric value, the value of ‘health’ - 1. It does not imply any assignment, you must perform the assignment yourself.
Has multiple atomar operations. You see them when writing it differently:
currentHealth = owner["health"]
#1: read container owner store value in an implizit variable
#2: create variable currentHealth
#3: assign result of 1 to variable of currentHealth
damageFromBullet = bullet["damage"]
armory = owner["armory"]
damageThroughArmory = damageFromBullet * armory
damagedHealth = currentHealth - damageThroughArmory
owner["health"] = damagedHealth # Add/Replace item with key "health" in container and value damagedHealth
This code seems longer but it does the same as the code above. The code above does not show the implizit variables.
Btw. It is not the goal of a good programmer to write code that is as short as possible. A professional programmer writes code that is as readable as possible.
Yes, the 10 - 2 is a separate example. Mathematical operations return the result, but you need to specifically instruct Python (just as in Mathematics) what you wish to do with the result.