HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Game character sprite positioning and movement

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
spritecharactermovementgameandpositioning

Problem

The player will have different spells that can be cast on different keyboard key combinations.

Right now what I have is one .as file with everything on it. A bunch of ifs, checking for combos if (combo="WW") {}, if (flightMode) {} and so on, which I know is bad practice and makes it confuse.

There will be more combos/different key combinations so I need to start learning neatness.

I'm looking for code correctness and best practices.

```
package
{
import flash.display.Sprite;
import flash.utils.getDefinitionByName;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;

import nape.geom.Vec2;
import nape.phys.Body;
import nape.phys.BodyList;
import nape.phys.BodyType;
import nape.shape.Polygon;
import nape.space.Space;
import nape.util.ShapeDebug;

public class Main extends Sprite
{
public var gravity:Number = 600;

public var space:Space = new Space(new Vec2(0, gravity));
public var antiGravity:Vec2 = new Vec2(0, -gravity);
public var impulse:Vec2 = new Vec2(0, 0);
public var flight:Vec2 = new Vec2(0, 0);

public var mainChar:Body = new Body(BodyType.DYNAMIC);

public var allow2ndKey:Boolean;
public var allow3rdKey:Boolean;
public var combo:String;
public var spellTimerStart:Boolean;
public var heroPosition:Boolean = true;
public var heroFlightMode:Boolean = false;
public var flightModeMovement:Boolean = false;

public var velChange:Number;
public var desiredVel:Number = -1800;
public var startingHeroY:Number;
public var spellTimer:Number = 70;

public var reset:Boolean = false;

public var flyUp:Number;
public var flyUpVel:Number = -150;
public var Up:Boolean;
public var Down:Boolean;
public var flyDown:Number;
public var flyDownVel:Number = 150;
public var Right:Boolean;
public var flyRight:Number;
public var flyRightVel:Number = 125;
public var Le

Solution

Single Responsibility Principle

"A class should have one, and only one, reason to change." (defined in The Principles of OOD)
You can use this principle to group parts of the code that have the same reason to change into classes. Imagine what changes you would need to make in order to add a new player spell or a new key combo, for example, then extract those into a class.

On the other hand, if you end up changing a class for more than one reason, then that class should be split into several classes with different reasons to change.

Context

StackExchange Code Review Q#58493, answer score: 3

Revisions (0)

No revisions yet.