Link to the project or level: (Game Lab - Code.org)
What I expect to happen: The target will have random velocity.
What actually happens: There is an error: “ERROR: Line: 34: TypeError: Cannot set property ‘velocityY’ of undefined”
What I’ve tried: I have tried checking the code multiple times.
Thank you!
Pleased to meet you @jennifer.hemry.
The root of your problem is actually not that hard to figure out.
You called the function setTarget(); before the target sprite was declared.
In summary, you just have to remove the line (that calls the function) on line 6 (as you also already called it when an if statement is an action, so no need to move it).
I hope this has helped you!
Thank you! That was easy! My brain is fried…four more days until Spring Break!
Greetings @jennifer.hemry,
While I agree with @pluto, I wanted to break down the error message that way the next time you encounter a similar runtime error you’ll know how to fix it
ERROR: Line: 34: TypeError: Cannot set property ‘velocityY’ of undefined
Lets start at where it’s telling us the error is, it may provide some insight
function setTarget() {
target.velocityY = randomNumber(10, 22);
target.y = 30;
target.x = randomNumber(50, 350);
}
Nothing seems wrong, which can mean a few things but I’ll point out the 2 obvious ones i can think of,
1:) Where the function is called
2:) Improper Parameters passed through (which yours doesn’t have)
Lets See where the function is called then of which 2 are found
// #6 and beyond
setTarget();
var target = createSprite(190, 60);
target.setAnimation("fly_1");
// #24 and beyond
if (target.y > 400) {
setTarget();
}
now you can probably see why the problem is persisting if not I’ll explain why it was a “TypeError” as it stands when line 6 is executed it jumps to line 33 and start it’s processes; then it gets to line 34 where target has not been declared globally yet. undefined has no properties or attributes to it’s name so basically on line 34, this is what it’s executing
// OG
target.velocityY = randomNumber(10, 22);
// execution
undefined.velocityY = randomNumber(10, 22);
since target is expected to be an Object() but received undefined you get a type error since undefined can’t have any value or properties which could also be considered a logic error in some cases in where the program runs and crashes after a certain action or amount of time has passed.
If you understood what it meant before my explanation that’s great! I’m just clarifying for future people who may view this post due to a similar TypeError question
All the best, Varrience