I am new to javascript.I want to move a car on path with arrows.I created the path with svg and made functions for the arrows.They are ok.But I dont know how will the car recognize the path?If I should check the path’s coordinates for each move, my path consists of different shapes how can I control it?I found some examples but they make the movement as motion not with each key press. Please give me an idea how to move the car only over the road..
Share
Ok, short answer: elements cannot recognize each other. What you can do, however, is simulate collisions by getting the computed styles of all elements you need, and then calculating the ‘surface’ the cover on the page. a couple of functions that will help you with that are
getComputedStyle()andcurrentStyle, the latter is IE’s equivalent of the first.Basically, you’ll have to bind a custom event to your car – or whatever element you need, that gets dispatched (or in IE lingo: Fired) each time a key is pressed. That event will have to recalculate change the style of your car/element. Example: the up key is pressed, so the y position must change. Before actually moving the element, you should have an object containing all positions of solid elements in the area. Scan that element to see if the new position your car element is moving to will cause an overlap, if so dispatch/Fire the collision event, if not move car…
Not this is a really simplified explanation but those are the steps you’ll most likely have to go through on each key press. That’s why I suggested reading up on custom events, handlers, event binding and dispatching.
If you do write this in pure JavaScript, I can promise you now, hand on heart, there is 1 thing you won’t have to read up on: why JavaScript developers hate IE so much, especially if you want your script to run on IE versions prior to IE9…
I’ll just end with this: a page to bookmark for stuff like this is javascriptkit. Also, you might prefer to use a framework like jQuery to get round the cross browser issues you will encounter.
Good luck!