Sprite collision

im using two (transparent background) .png images as sprites. Both are of same width and height. And both have the same starting point.
But one image is on lower half of one sprite, and the other image is on upper half. Non-transparent (visible) parts of the images collides only at one point. Even though sprites meets at only one point the method below always returns true.
I used this method to check the collision.
What's wrong with my code ?
boolean checkCollision(){
    if(sprite_car.collidesWith(sprite_man,true)){
      return true;
    } else return false;
  }hope this info is enough .If anyone need more info pls let me know.
Thanx in advance !

hi,
incase you have not yet found the answer, can you post the code here?

Similar Messages

  • Events Triggered By Collision Detection In Shockwave 3D Environment Happen More Than Once?

    Okay, I've finally managed to get my Director 3D game to move an object to a new random position when collision detection occurs with that object! HOWEVER, sometimes it will work as expected and other times the object seems to move SEVERAL times before settling. Anyone have any idea why it isn't always just moving once and settling as I'd hoped it would...?
    To see an example of the problem I'm facing, create a new Director movie then insert a new Shockwave 3D media element into that Director movie named "Scene" and apply the below code to that 3D media element. I've tried to trim the code down as much as possible to get right to the heart of the problem:
    =====
    property Scene  -- reference to 3D cast member
    property pSprite    -- referebce to the 3D sprite
    property pCharacter -- reference to the yellow in the 3D world
    property pTransformgreen01Flag -- reference to the flag which will trigger action to move green01 + increase score on collision
    property pTransformgreen02Flag -- reference to the flag which will trigger action to move green02 + increase score on collision
    on beginSprite me
      -- initiate properties and 3D world
      pSprite = sprite(me.spriteNum)
      Global Scene
      Scene = sprite(me.spriteNum).member
      Scene.resetWorld()
      Tempobjres = Scene.newmodelresource("sphereRES", #sphere)  --create sphere modelresource
      Tempobjres.radius = 10     --set sphere modelresrource radius to 20
      Tempobjres.resolution = 17   --set the sphere modelresource resolution to 17
      Tempobj = scene.newmodel("yellow", tempobjres)   --create a model from the sphere modelresource
      Tempshader = scene.newshader("sphereshd", #standard)   --create a new standard shader
      Tempshader.diffuse = rgb(250,250,10)   --set the diffuse color (in this case, a light green)
      Tempshader.texture = void   --set the texture of the shader to void
      Tempobj.transform.position=vector(0,0,0)
      Tempobj.shaderlist = tempshader   -- assign the shader to the model
      Tempobjres1 = Scene.newmodelresource("sphereRES1", #sphere)  --create sphere modelresource
      Tempobjres1.radius = 10     --set sphere modelresrource radius to 20
      Tempobjres1.resolution = 17   --set the sphere modelresource resolution to 17
      Tempobj1 = scene.newmodel("green01", tempobjres1)   --create a model from the sphere modelresource
      Tempshader1 = scene.newshader("sphereshd1", #standard)   --create a new standard shader
      Tempshader1.diffuse = rgb(100,200,50)   --set the diffuse color (in this case, a light green)
      Tempshader1.texture = void   --set the texture of the shader to void
      Tempobj1.transform.position = vector(25,25,0)
      Tempobj1.shaderlist = tempshader1   -- assign the shader to the model
      Tempobjres2 = Scene.newmodelresource("sphereRES2", #sphere)  --create sphere modelresource
      Tempobjres2.radius = 10     --set sphere modelresrource radius to 20
      Tempobjres2.resolution = 17   --set the sphere modelresource resolution to 17
      Tempobj2 = scene.newmodel("green02", tempobjres2)   --create a model from the sphere modelresource
      Tempshader2 = scene.newshader("sphereshd2", #standard)   --create a new standard shader
      Tempshader2.diffuse = rgb(100,200,50)   --set the diffuse color (in this case, a light green)
      Tempshader2.texture = void   --set the texture of the shader to void
      Tempobj2.transform.position = vector(-25,-25,0)
      Tempobj2.shaderlist = tempshader2   -- assign the shader to the model
      --the following lines will add collision detection for all three on-screen 3D objects
      Tempobj.addModifier(#collision)
      Tempobj.collision.enabled=true
      Tempobj1.addModifier(#collision)
      Tempobj1.collision.enabled=true
      Tempobj2.addModifier(#collision)
      Tempobj2.collision.enabled=true
      Tempobj.collision.resolve=true
      Tempobj1.collision.resolve=true
      Tempobj2.collision.resolve=true
      --the following lines will tell Director what to do with a specific object when it collides with another
      Tempobj.collision.setCollisionCallBack(#beepsound, me)
      Tempobj1.collision.setCollisionCallBack(#hitgreen01, me)
      Tempobj2.collision.setCollisionCallBack(#hitgreen02, me)
      pCharacter = Scene.model("yellow")
      -- we must define pCharacter after we use the resetWorld() command
      -- otherwise this variable object will be deleted
      createCollisionDetect
      pTransformgreen01Flag = false
      pTransformgreen02Flag = false
    end
    on createCollisionDetect
      Global Scene
      -- add collision modifier to the character
      pCharacter.addmodifier(#collision)
      -- set bounding geometry for collision detection to bounding box of model
      pCharacter.collision.mode = #mesh
      -- resolve collision for character
      pCharacter.collision.resolve = TRUE
    end
    on keyDown
      Global Scene
      case(chartonum(the keypressed)) of
        30: --up arrow
          scene.model("yellow").translate(0,5,0)
        31: --down arrow
          scene.model("yellow").translate(0,-5,0)
        28: --left arrow
          scene.model("yellow").translate(-5,0,0)
        29: --right arrow
          scene.model("yellow").translate(5,0,0)
      end case
    end
    --when "yellow" (player character) hits another object, this will happen:
    on beepsound me, colData
      beep --plays sound
    end
    --when "green01" is hit by another object, this will happen:
    on hitgreen01 me, colData
      Global Scene
      pTransformgreen01Flag=true
    end
    --when "green02" is hit by another object, this will happen:
    on hitgreen02 me, colData
      Global Scene
      pTransformgreen02Flag=true 
    end
    on enterFrame me
      Global Scene
      if pTransformgreen01Flag then
        --the following lines will generate new random x and y co-ordinates for green01
        randomx=random(-110,110)
        green01x=randomx
        randomy=random(-90,90)
        green01y=randomy
        Scene = member("Scene")
        Scene.model("green01").transform.position = vector(green01x,green01y,0)
        pTransformgreen01Flag = false
      end if
      if pTransformgreen02Flag then
        --the following lines will generate new random x and y co-ordinates for green02
        randomx=random(-110,110)
        green02x=randomx
        randomy=random(-90,90)
        green02y=randomy
        Scene = member("Scene")
        Scene.model("green02").transform.position = vector(green02x,green02y,0)
        pTransformgreen02Flag = false
      end if
    end
    =====
    I imagine the part that's causing the issue is the "on enterFrame me" part at the end, but can't see any reason why it wouldn't just perform the desired action ONCE every time...?
    This is really confusing the hell out of me and is pretty much the final hurdle before I can call my game "finished" so any and all assistance would be GREATLY appreciated!

    You can get yourself a used copy of my book http://www.amazon.com/Director-Shockwave-Studio-Developers-Guide/dp/0072132655/ for $0.82 + shipping.  Chapter 14 contains 33 pages which deal specifically with the vagaries of the collision modifier.
    You can download just the chapter on Collision Detection from http://nonlinear.openspark.com/book/Collisions.zip.  This includes the demo movies and the unedited draft of the text for the chapter.
    Perhaps you will find this useful.

  • Camera Collision Detection - Is It Possible?

    Hi,
    I am making a 3D RPG game and I would like to know if it is possible to get collision detection on a camera created in Adobe Director 11.  I have my 3D character running through an underground maze and he detects correctly on the walls of the maze.  However, I also have a camera as a child to the character so this moves with him.  I have added a bounding-box to this camera but it still doesn't detect whereas the gunBB works fine, as does the characterBB.
    This is really confusing and I don't know what I am doing wrong.  Any help would be really appreciated!
    Thanks, Phil.

    Thanks for the reply.  It is not exactly what I am looking for as the script is different than the style I am using.  This is the script I have got so far, I have also added an extra camera to view what is happening.
    property pSprite, p3Dmember -- reference to the 3D member
    --property pLevel, maze -- Level
    --property pLeftArrow, pRightArrow, pDownArrow, pUpArrow -- arrow keys
    --property pCharacter -- character in the 3D world
    --property pTofuBB, pGunBB, gun --  character + gun
    --property gUseGun, hasGun
    --property pCamera, pCameraBoundingBox --camera and bounding box
    --property barrier,mountains,exitmaze
    --property door1, door2, turret, turretgun
    --property keylist, keypresslist -- for keys pressed
    --on beginSprite me
    --  -- define the 3D cast member
    --  p3Dmember = sprite(me.spriteNum).member
    --  -- reset the 3D world
    --  p3Dmember.resetWorld()
    --  pSprite = sprite(me.spriteNum)
    --  pCamera = pSprite.camera
    --  -- define level as 3DS level Plane - must all be defined after resetWorld()
    --  pLevel = p3Dmember.model("landscape")
    --  mountains = p3Dmember.model("mountains")
    --  turret = p3Dmember.model("turret")
    --  turretgun = p3Dmember.model("turretgun")
    --  maze = p3Dmember.model("maze")
    --  exitmaze = p3Dmember.model("exitmaze")
    --  pCharacter = p3Dmember.model("hero")
    --  gun = p3Dmember.model("gun")
    --  barrier = p3Dmember.model("barrier")
    --  door1 = p3Dmember.model("door1")
    --  door2 = p3Dmember.model("door2")
    --  -- stop hero walking biped animation
    --  pCharacter.bonesPlayer.pause()
    --  -- below for key control
    --  keylist = []
    --  keypresslist = []
    --  -- this sets up a list of keycodes to track.
    --  -- this code covers the arrow keys only, it could be changed to cover a full range of keys
    --  repeat with i = 123 to 126
    --    keylist[i] = i -- this creates a list of keycodes to track
    --    keypresslist[i] = 0 -- this creates a "last state" list that corresponds to the keycode.
    --    --keypresslist tracks the last known state of that key, so we can tell when a keypress has changed.
    --  end repeat
    --  -- key control end
    --  createBoundingBoxes
    --  createLight
    --end
    -- code used to create bounding boxes
    --on createBoundingBoxes
    --  -- create tofu bounding box for character
    --  tofuBB_MR = p3Dmember.newModelResource("tofuBox",#box)
    --  tofuBB_MR.height = 235
    --  tofuBB_MR.width = 235
    --  tofuBB_MR.length = 500
    --  pTofuBB = p3Dmember.newModel("tofuBox",tofuBB_MR)
    --  pTofuBB.worldPosition = pCharacter.worldPosition
    --  -- create parent child relationships
    --  pCharacter.addChild(pTofuBB, #preserveWorld)
    --  invisShader = p3Dmember.newShader("invisShader",#standard)
    --  invisShader.transparent = TRUE
    --  invisShader.blend = 50
    --  pTofuBB.shaderlist = p3Dmember.shader("invisShader")
    --  pCamera = p3Dmember.newCamera("camera")
    --  frontCam = p3Dmember.newCamera("frontCam")
    --  frontCam.fieldOfView = 35
    --  frontCam.transform.position = vector(-14150,-3100,-600)
    --  frontCam.transform.rotation = vector(90,0,180)
    --  pSprite.camera = p3Dmember.camera("frontCam")
    --  pCamera.fieldOfView = 75
    --  pCamera.transform.position = vector(500,1800,450) --450
    --  pCamera.transform.rotation = vector(90,0,180)
    --  pSprite.camera = p3Dmember.camera("camera")
    --  cameraModRes = p3Dmember.newModelResource("cameraModRes",#sphere)
    --  cameraModRes.radius = 200
    --  pCameraBoundingBox = p3Dmember.newModel("CameraBoundingBox",cameraModRes)
    --  pCameraBoundingBox.worldPosition = pCamera.worldPosition
    --  pCameraBoundingBox.shaderList = p3Dmember.shader("invisShader")
    --  pCamera.addChild(pCameraBoundingBox, #preserveWorld)
    --  pCharacter.addChild(pCamera,#preserveWorld)
    --  -- create gun bounding box
    --  gun.worldposition.z = gun.worldposition.z + 200
    --  gunMR = p3Dmember.newModelResource("gunSphere",#sphere)
    --  gunMR.radius = 218
    --  pGunBB = p3Dmember.newModel("gunSphere", gunMR)
    --  pGunBB.worldPosition = gun.worldPosition
    --  pGunBB.shaderList = p3Dmember.shader("invisShader")
    --  pGunBB.addChild(gun, #preserveWorld)
    --end
    -- code below used to light up level
    --on createLight
    --  -- create a point 'bulb' type light
    --  p3Dmember.newLight("Bulb Light", #point )
    --  -- position the light
    --  p3Dmember.light("Bulb Light").transform.position = vector(0,0,100)
    --  -- define light color and intensity
    --  p3Dmember.light("Bulb Light").color = rgb(255,255,255)
    --  -- Make the character model a parent of the light
    --  -- Bulb Light becomes a child of pCharacter
    --  -- This is done so that the light will always move
    --  -- with the character.
    --  pCharacter.addChild(p3Dmember.light("Bulb Light"),#preserveParent)
    --end
    --on keyUp me
    --  --pCharacter.bonesPlayer.pause()
    --  --if keypressed("s")
    --end
    --on keydown me
    --  if keypressed("c") then changeCamera
    --end
    --on changeCamera
    --  -- check the sprites camera and switch
    --  if pSprite.camera = p3Dmember.camera("frontCam") then
    --     pSprite.camera = p3Dmember.camera("camera")
    --     else
    --     pSprite.camera = p3Dmember.camera("frontcam")
    --     end if
    --end
    --on exitFrame me
    -- below detects which keys are pressed
    --repeat with i = 1 to keylist.count
    --inewstate= keypressed( keylist[i] )
    --if keypresslist[i] <> inewstate then -- this means the key changed status from whether it's up or down
    --if inewstate= 0 then
    -- they key was released
    --keyLastReleased = keylist[i]
    --if (keyLastReleased=123) then pLeftArrow = 0 -- 123 = left arrow key
    --if (keyLastReleased=124) then pRightArrow = 0 -- 124 = right arrow key
    --if (keyLastReleased=125) then
    --pDownArrow = 0 -- 125 = down arrow key
    --pCharacter.bonesPlayer.pause()
    --end if
    --if (keyLastReleased=126) then
    --pUpArrow = 0 -- 126 = up arrow key
    --pCharacter.bonesPlayer.pause()
    --end if
    --else
    -- the key was pressed
    --keyLastPressed = keylist[i]
    --if (keyLastPressed=123) then pLeftArrow = 1 -- 123 = left arrow key
    --if (keyLastPressed=124) then pRightArrow = 1 -- 124 = right arrow key
    --if (keyLastPressed=125) then pDownArrow = 1 -- 125 = down arrow key
    --if (keyLastPressed=126) then pUpArrow = 1 -- 126 = up arrow key
    --end if
    --keypresslist[i] = inewstate-- update so we remember its new state.
    --end if
    --end repeat
    -- by the time this repeat loop has finished, keypresslist will contain a complete index of what keys
    -- are held down, and which aren't.
    -- Note: most keyboards have a limit on how many keys they'll track simultaneously.
    --checkCollisions
    --characterMove
    -- gun collision start
    --if gUseGun = TRUE then
    --pTofuBB.addChild(pGunBB,#preserveParent)
    --pGunBB.worldPosition = pTofuBB.worldPosition
    --pGunBB.worldPosition.z = 500
    --pGunBB.worldPosition.x = pCharacter.worldPosition.x - 150 --50
    ---pGunBB.worldPosition.y = -860
    --pGunBB.rotate(0,0,-240)
    --pCharacter.bonesPlayer.pause()
    --gUseGun = FALSE
    --hasGun = TRUE
    --end if
    -- gun collision end
    --end
    --on characterMove
    -- if the right arrow is pressed,
    -- rotate the character 5 degrees about the z-axis
    --if pRightArrow then
    -- rotate character and camera
    --pCharacter.rotate(0,0,-2)
    --end if
    --if the left arrow is pressed,
    -- rotate character -5 degrees about the z-axis
    --if pLeftArrow then
    --pCharacter.rotate(0,0,2)
    --end if
    -- if the up arrow is pressed,
    -- move the character 5 pixels along the y-axis
    --if pUpArrow then
    --if (pcharacter.bonesPlayer.playing = 0) then
    --pCharacter.bonesplayer.loop = true
    --if (_key.shiftDown) then
    --pCharacter.bonesPlayer.playRate = 2
    --if (hasGun = TRUE) then -- running
    --pCharacter.bonesplayer.play("hero", 1, 6270, 8330, 1)
    --else
    --pCharacter.bonesplayer.play("hero", 1, 2067, 4130, 1)
    --end if
    --else
    --pCharacter.bonesPlayer.playRate = 1
    --if (hasGun = TRUE) then -- walking
    --pCharacter.bonesplayer.play("hero", 1, 4200, 6200, 1)
    --else
    --pCharacter.bonesplayer.play("hero", 1, 0, 2000, 1)
    --end if
    --end if
    --end if -- bonesPlayer playing
    --if (_key.shiftDown) then
    --pCharacter.translate(120,0,0)
    --else
    --pCharacter.translate(50,0,0)
    --end if
    --end if
    -- if the down arrow is pressed,
    -- move the character -5 pixels along the y-axis
    --if pDownArrow then
    --if (pcharacter.bonesPlayer.playing = 0) then
    --pCharacter.bonesplayer.loop = true
    --if (_key.shiftDown) then
    --pCharacter.bonesPlayer.playRate = 2
    --if (hasGun = TRUE) then -- running
    --pCharacter.bonesplayer.play("hero", 1, 6270, 8330, 1)
    --else
    --pCharacter.bonesplayer.play("hero", 1, 2067, 4130, 1)
    --end if
    --else
    --pCharacter.bonesPlayer.playRate = 1
    --if (hasGun = TRUE) then -- walking
    --pCharacter.bonesplayer.play("hero", 1, 4200, 6200, 1)
    --else
    --pCharacter.bonesplayer.play("hero", 1, 0, 2000, 1)
    --end if
    --end if
    --end if -- bonesPlayer playing
    --if (_key.shiftDown) then
    --pCharacter.translate(-120,0,0)
    --else
    --pCharacter.translate(-50,0,0)
    --end if
    --end if
    -- floor collision
    --thisPosn = pTofuBB.worldPosition
    -----thisPosn.z = 1000
    --tModelList = [pLevel, maze, door1, door2] -- removed wall as its no longer on level
    --tOptionsList = [#levelOfDetail: #detailed, #modelList: tModelList]
    --thisData = p3Dmember.modelsUnderRay(thisPosn,vector(0,0,-1),tOptionsList)
    --if thisData.count then
    --totalCount = thisData.count
    --repeat with dataIndex = 1 to totalCount
    --terrainPosn = thisData[dataIndex].isectPosition
    --- if (thisData[dataIndex].model = pLevel) then
    --tDiff = (terrainPosn.z - pTofuBB.worldPosition.z) + 375
    --pCharacter.translate(0,0,tDiff,#world)
    --exit repeat
    --end repeat
    --end if
    --end
    --on checkCollisions
    --tModelList = [pGunBB, barrier, mountains, maze, exitmaze, turret, turretgun]
    --tOptionsList = [#maxNumberOfModels: 2, #levelOfDetail: #detailed, #modelList: tModelList, #maxDistance: 300]
    -- make 4 rays around character checking for collisions, 90 degrees apart
    --repeat with i = 1 to 18
    --pCharacter.rotate(0,0,20,#self)
    --returnData = p3Dmember.modelsUnderRay(pCharacter.worldPosition,pCharacter.transform.xAxis,tOptionsList )
    --if (returnData.count) then
    -- first in array is closest
    --checkObjectFoundDistance(returnData[1])
    --end if
    --end repeat
    --end
    --on checkObjectFoundDistance thisData -- check distance from collision with objects
    --dist = thisData.distance
    -- check if distance is less than width of bounding box
    --if (dist < 150) then
    --case thisData[#model].name of
    --"gunSphere":
    --gUseGun = TRUE
    --"barrier":
    -- get distance of penetration
    --diff = 150 - dist
    -- calculate vector perpend icular to the wall's surface to move the character
    -- using the #isectNormal property
    --tVector = thisData.isectNormal * diff
    -- move the character in order to resolve the collision
    --pCharacter.translate(tVector,#world)
    --end case
    --end if
    --if (dist < 150) then
    --case thisData[#model].name of
    --"gunSphere":
    --gUseGun = TRUE
    --"mountains":
    -- get distance of penetration
    --diff = 150 - dist
    -- calculate vector perpend icular to the wall's surface to move the character
    -- using the #isectNormal property
    --tVector = thisData.isectNormal * diff
    -- move the character in order to resolve the collision
    --pCharacter.translate(tVector,#world)
    --end case
    --end if
    --if (dist < 150) then
    --case thisData[#model].name of
    --"gunSphere":
    --gUseGun = TRUE
    --"maze":
    -- get distance of penetration
    --diff = 150 - dist
    -- calculate vector perpend icular to the wall's surface to move the character
    -- using the #isectNormal property
    --tVector = thisData.isectNormal * diff
    -- move the character in order to resolve the collision
    --pCharacter.translate(tVector,#world)
    --end case
    --end if
    --if (dist < 150) then
    --case thisData[#model].name of
    --"gunSphere":
    --gUseGun = TRUE
    --"exitmaze":
    -- get distance of penetration
    --diff = 150 - dist
    -- calculate vector perpend icular to the wall's surface to move the character
    -- using the #isectNormal property
    --tVector = thisData.isectNormal * diff
    -- move the character in order to resolve the collision
    --pCharacter.translate(tVector,#world)
    --end case
    --end if
    --if (dist < 150) then
    --case thisData[#model].name of
    --"gunSphere":
    --gUseGun = TRUE
    --"turret":
    -- get distance of penetration
    --diff = 150 - dist
    -- calculate vector perpend icular to the wall's surface to move the character
    -- using the #isectNormal property
    --tVector = thisData.isectNormal * diff
    -- move the character in order to resolve the collision
    --pCharacter.translate(tVector,#world)
    --end case
    --end if
    --if (dist < 150) then
    --case thisData[#model].name of
    --"gunSphere":
    --gUseGun = TRUE
    --"turretgun":
    -- get distance of penetration
    --diff = 150 - dist
    -- calculate vector perpend icular to the wall's surface to move the character
    -- using the #isectNormal property
    --tVector = thisData.isectNormal * diff
    -- move the character in order to resolve the collision
    --pCharacter.translate(tVector,#world)
    --end case
    --end if
    --end

  • How to intersect with any sprite of a certain cast member?

    Hi. I am trying to script a simple 2d platformer engine for a larger University project. I have movement sorted with W and A and gravity. I can get collision detection with the floor by doing
    if sprite 1 intersects sprite 2 then
         gvGrav = 0
    end if
    Sprite 1 is the player and sprite 2 is an instance of the cast member called ground. How would I get this to work with any sprite that is ground? Ill paste the full code below.
    global gvRight
    global gvLeft
    global gvGrav
    global gvDown
    on enterFrame
      -----------MOVE LEFT---------------------
      if keyPressed("a") then
        sprite(4).locH=sprite(4).locH+gvLeft
        _movie.updateStage()
        gvLeft = gvLeft - .5
        if gvLeft < - 15 then
          gvLeft = -15
        end if
      end if
      if not keypressed("a") then
        gvLeft = 0
      end if
      -----------MOVE RIGHT--------------------
      if keyPressed("d") then
        sprite(4).locH=sprite(4).locH+gvRight
        _movie.updateStage()
        gvRight = gvRight + .5
        if gvRight > 15 then
          gvRight = 15
        end if
      end if
      if not keypressed("d") then
        gvRight = 0
      end if 
      -----------GRAVITY-------------------------
      gvGrav = gvGrav
      sprite(4).locV=sprite(4).locV+gvGrav
      _movie.updateStage()
      gvGrav = gvGrav +.5
      if gvGrav > 30 then
        gvGrav = 30
      end if
      -------------GravityCollision----------------------
      if sprite 4 intersects sprite 1 then
        gvGrav = 0
      end if
      if sprite 4 intersects sprite 2 then
        gvGrav = 0
      end if
    end if

    I dare say there's a better way to do this, but an easy way is to set a global variable, do a sendallsprites message, and check the global variable again.
    So, if you had an extra global in your man control script:
    global hitman
    then in your collision checking part you would say this:
      hitman = false
      sendallsprites #checkcollision 4
      if hitman = true then
        gvGrav = 0
      end if
    The #checkcollision message would get sent to all sprites, and if you had a behavior placed on the floor sprites, that was like this:
    global hitman
    property mysprite
    on beginsprite me
      mysprite = the spritenum of me
    end
    on checkcollision me,s
      if sprite s intersects sprite mysprite then
        hitman = true
      end if
    end
    any one of those sprites that intersected with the sprite you ask about would then change the global 'hit man' variable to be true. To make a sprite behave like floor, you would just attach that behavior script.
    Notice how the floor sprite makes a note of its sprite number when it first shows up on the stage, you could do the same with your other script, if it's attached to the man character. Then you wouldn't have to have it hard coded to '4', which would save some headaches later if you have to change the sprite layers.

  • Random movement within an irregularly constrained sprite (EDITED)

    (NEW EDIT AT BOTTOM)
    So, basically, I'm making a little program that crudely simulates an ant colony. I have little tunnels the ant-sprites can travel down, as well as chambers, in an irregularly-shaped sprite.
    I am not the most advanced at Director, but at least I've figured some things out. I found code on an open-source website (openspark, actually) that allows for an object to be dragged inside an irregular shape that has a matte ink.
    It's all well and good that the ants can be dragged within this boundary, but is there any way to have them use a Random Movement and Rotation behavior that is confined by the same laws? Or is that impossible / extremely hard?
    By the way, I already have a middleman behavior I use to toggle between dragging and random movement, so that does not factor into my question. I just need to know how to alter the Random Movement behavior so that it abides by the same constraint rules as my dragging behavior, if possible.
    Here is the code I'm using for dragging. I made a couple edits from the original, but not much.
    Don't worry about the canJumpGaps function of this code, as I am using a touch screen and it will never be used.
    property spriteNum
    property canJumpGaps    
    -- set to TRUE on mouseDown if the shiftDown
    property pSprite
    -- this draggable sprite
    property pConstraintSprite
    -- sprite to which this sprite is constrained
    property pConstraintAlpha
    -- alpha channel image of constraining member
    property pOffset
    -- offset between this sprite's loc and the mouse
    property pCurrentLoc
    -- last known position of this draggable sprite with respect to the constraining sprite
    -- EVENT HANDLERS --
    on beginSprite(me)
      pSprite  = sprite(spriteNum)
      pConstraintSprite = sprite(1)
      -- We'll use the value of the alpha channel to detect holes in the sprite
      pConstraintAlpha  = pConstraintSprite.member.image.extractAlpha()
    end beginSprite
    on mouseDown(me)
      canJumpGaps = the shiftDown
      if not pCurrentLoc then
        -- The user has not yet dragged the sprite anywhere.  Find out its
        -- current position with respect to the constraint sprite.
        pCurrentLoc = pConstraintSprite.mapStageToMember(pSprite.loc)
        if not pCurrentLoc then
          -- The mouse is not over an opaque part of the constraint
          -- sprite.  It can't be dragged at all.
          exit
        end if
      end if
      -- Start dragging
    pOffset = pSprite.loc - the mouseLoc
    end mouseDown
    on exitFrame(me)
      if not pOffset then
        -- The user is not dragging the sprite
        exit
      end if
    if the mouseDown then
        me.mMoveSprite()
      else
        -- The user just released the mouse
       pOffset = 0
      end if
    end exitFrame
    -- PRIVATE METHOD --
    on mMoveSprite(me) ---------------------------------------------------
      -- SENT BY exitFrame()
      -- ACTION: Calculates how near to the current mouseLoc the draggable
      --         sprite can be dragged.
      tMouseLoc = the mouseLoc + pOffset
      -- Find where the mouse is with respect to the constraint member
    tImageLoc = pConstraintSprite.mapStageToMember(tMouseLoc)
      if voidP(tImageLoc) then
        -- The mouse is currently outside the constraint sprite.  Use a
        -- slower but more powerful method of determining the relative
        -- position.
        tLeft = pConstraintSprite.left
        tTop = pConstraintSprite.top
        tImageLoc = tMouseLoc-point(tLeft, tTop)
      else if canJumpGaps then
        -- Check if the mouse is over a non-white area of the constraint
        -- member
       tAlpha = pConstraintAlpha.getPixel(tImageLoc, #integer)
      end if
      if tAlpha then
        -- Let the mouse move to this spot
    else -- Can't jump gaps or the mouse is over a gap
        -- Find how near the dragged sprite can get
        tDelta  = pCurrentLoc - tImageLoc
        tDeltaH = tDelta.locH
        tDeltaV = tDelta.locV
        tSteps = max(abs(tDeltaH), abs(tDeltaV))
        if not tSteps then
          -- The mouse hasn't moved since the last exitFrame
          exit
        end if
        tSteps = integer(tSteps)
    if float(tSteps) <> 0 then
    tStep  = tDelta / float(tSteps)
    -- This makes sure I'm not dividing by zero.
    else
    tStep  = 1
    end if
    repeat while tSteps
    -- Move one pixel towards the mouse
    tSteps = tSteps - 1
    tLoc = tImageLoc + (tStep * tSteps)
    -- Test that we are still on an opaque area
    tAlpha = pConstraintAlpha.getPixel(tLoc, #integer)
    if not tAlpha then
    -- We've gone a step too far: move back to an opaque area
    tSteps = tSteps + 1
    exit repeat
    end if
    end repeat
    end if
    -- Update the absolute and relative positions of the draggable
    -- sprite.
    tAdjust     = tSteps * tStep
    pCurrentLoc = tImageLoc + tAdjust -- relative to constrain sprite
    tMouseLoc   = tMouseLoc + tAdjust -- relative to the stage
    -- Move the sprite
    pSprite.loc = tMouseLoc
    end mMoveSprite
    Thank you SO incredibly much to anyone who can help. This is for a senior project of mine in undergrad, and I really appreciate any help I can get. My resources on Director are limited, especially for odd issues like this.
    EDIT:
    So I found out that a way to do collision detection in Director is by using getPixel().
    I found this protected dcr file that is a perfect example of the way in which I want my ant objects to interact with walls:
    http://xfiles.funnygarbage.com/~colinholgate/dcr/irregular.dcr
    I've been trying to build a getPixel() collision detection mechanism for hours but have been unsuccessful.
    Basically, what I want the behavior to do is... get the pixel color of the tunnel sprite (sprite 2) at the center of the ant sprite. If the pixel color is white (the transparent background color surrounding the tunnel shape), I want to tell the Random Movement and Direction behavior this:
    pSprite.pPath = VOID
    sendSprite(pSprite, #mNewPath)
    pSprite.pRotate = VOID
    sendSprite(pSprite, #mNewRotation)
    This tells the Random Movement behavior to stop moving and determine a new path. The behavior should probably also offset the center of the sprite by a couple pixels when this happens so it is no longer over an opaque area and the Random Movement behavior won't get stuck.
    Will this work? If not, could anyone help me in building a collision detection behavior based on getPixel? This doesn't seem like it'd be all that difficult - at least in theory.

    Hi Roberto,
    I had an experience, which defies most common sense about data modeling. Moving from a cube to a ODS and then back on to a cube to introduce delta on a BPS delta application. It is a long sad disappointing store. But I had 24 keys (I know 16 is the max, I combined 6 keys into a single filed also had the same fileds in the data fileds, use these combination keys to deal with 16 key max limitation and adjusted during transformation.
    It did work, but later gave up due to some other functional issues and we realized it is a bad experiement due to everyones data understanding.
    I am saying is 16 key limitation is an issue, you can overcome with combining couple of fileds into a single filed in the start routine, map it and reuse it later.
    Hope this gives you some ideas.
    Goodluck,
    Alex (Arthur Samson)

  • Spawning multiple instances of a sprite (firing bullets).  Help needed.

    Hello there.  I'm currently trying to make a game in director 11.5 for a University project.  I've decided to make a scrolling space shooter but I've run into a problem.  Any tutorial I've found has created a limited 'bank' of bullets to fire, only allowing a certain number on the stage at any given time.  What I need to do is to leave a single bullet sprite off the boundaries of the page and essentially copy it and it's lingo behaviors to spawn another instance of the bullet on the stage when the player fires (using the left mouse button in this case).  I also need this copy to be deleted entirely when it collides with an enemy or leaves the boundaries of the stage, otherwise the game will just run slower and slower as more shots are fired.
    I have heard that this is possible using the puppetSprite() method but the API doesn't shine much light on the issue and neither has literally hours of google searches.  If anyone can let me know any method of doing this, I'd be very grateful.
    On a related issue, when fired the bullet will need to intsect the location of where the mouse cursor was when the bullet was fired and then continue on a linear path.  I've worked out a method of doing this but it isn't very effective or efficient (the speed of the bullets would be determined by how far away the mouse cursor is from the players ship and I think there's probably a less calculation intensive method for doing this) and as I can't spawn the bullets as of now, I really don't know if it will even work.  If anyone has any advice on how to better implement this mechanic, again I'd welcome your input.  Thanks in advance.

    You want to work with objects not numbers which means using Points for locs and Sprite references and not sprite numbers.
    I feel that using a object manager object would make programming this a lot easier, cleaner, and more efficient. Rather than give a lecture on OOP and OOD, I took some of Josh's ideas like using a timeout object and wrote some scripts in my style to give you something else to boggle your brain.
    I tested these scripts but not thoroughly and I left plenty for you to do.
    I separated out the creation and control of "bullets" from the movement of the bullets. So, there is a behavior that does nothing more than move the bullet sprites and the control object handles everything else using a single timeout object.
    I suggest creating a new project to play with these scripts. Throw a bunch of sprites on the stage and attach the "Hitable Sprite" behavior to them, make sure you have a sprite named "bullet", and a " go the frame" behavior to loop on and you should be good to go.
    Note that where I set the velocity of the bullet sprites, that I use "100.0" instead of 20.  20 would be a very fast speed.
    Here's the Parent script for the control:
    -- Bullet Control parent script
    property  pUpdateTimer  -- timeout object for doing updates
    property  pBullets  -- list of bullet sprites
    property  pGunLoc  -- location of the gun, ie the location where your bullets start at.
    property  pRightBounds  -- right edge of the stage
    property  pBottomBounds  -- bottom edge of the state
    property  pZeroRect  -- used for intersection hit detection
    on new me
      pUpdateTimer = timeout().new("BulletCntrl", 25, #update, me)  -- 25 milleseconds = 40 updates per second
      pBullets = []
      pGunLoc = point(300,550)  -- *** SET THIS to where you want your bullets to start at.
      pZeroRect = rect(0,0,0,0)
      -- store stage bounds for later use
      pRightBounds = _movie.stage.rect.width
      pBottomBounds = _movie.stage.rect.height
      return me
    end new
    on fire me
      NewBullet = script("Bullet behavior").new(pGunLoc)  -- create new bullet sprite
      if ilk(NewBullet, #sprite) then pBullets.add(NewBullet)  -- store sprite reference
    end fire
    on update me, timeob
      if pBullets.count = 0 then exit  -- no bullets to update
      -- update bullet positions
      call(#update, pBullets)
      -- get list of sprites to test for hits/collisions
      HitSprites = []
      sendAllSprites(#areHitable, HitSprites)  -- the list "HitSprites" is populated by each hitable sprite.
      BulletsToDelete = []  -- list of bullet sprites to delete
      -- check if any bullet has hit a hitable sprite
      repeat with Bullet in pBullets
        repeat with HitSprite in HitSprites
          if Bullet.rect.intersect(HitSprite.rect) <> pZeroRect then
            HitSprite.explode()
            BulletsToDelete.add(bullet)
            exit repeat  -- leave inner loop
          end if
        end repeat
      end repeat
      -- check if bullet is out of bounds
      repeat with Bullet in pBullets
        Die = false
        if Bullet.right < 0 then Die = true
        if Bullet.left > pRightBounds then Die = true
        if Bullet.top > pBottomBounds then Die = true
        if Bullet.bottom < 0 then Die = true
        if Die then BulletsToDelete.add(Bullet)
      end repeat
      -- remove any sprites that hit something or went off the screen
      repeat with Bullet in BulletsToDelete
        Bullet.die()
        pBullets.deleteOne(Bullet)  -- remove bullet from list of active bullets
      end repeat
    end update
    on stopMovie
      -- end of app cleanup
      if pUpdateTimer.objectP then
        pUpdateTimer.forget()
        pUpdateTimer = void
      end if
    end
    The behavior for the bullets is:
    -- Bullet behavior
    property  pMe
    property  pVelocity
    property  pCurLoc
    on new me, StartLoc
      -- get a sprite
      pMe = me.getSprite()
      if pMe.voidP then return void  -- if not a sprite then give up
      -- setup this bullet sprite
      pMe.puppet = true
      pMe.member = member("bullet")
      pMe.loc = StartLoc
      pMe.scriptInstanceList.add(me)  -- add this behavior to this sprite
      -- set velocity
      pVelocity = ( _mouse.mouseLoc - StartLoc) / 100.0  -- Note: magic number "20.0"
      updateStage()  -- need to update pMe.rect values
      pCurLoc = pMe.loc -- store current location
      return pMe  -- Note: returning "pMe" not "me"
    end new
    on getSprite me
      repeat with CurChannel = 1 to the lastchannel
        if sprite(CurChannel).member = (member 0 of castLib 0) AND sprite(CurChannel).puppet = false then
          return sprite(CurChannel)
        end if
      end repeat
      return void
    end getSprite
    on update me
      -- move bullet. 
      pCurLoc = pCurLoc + pVelocity  -- add velocity to pCurLoc to maintain floating point accuracy
      pMe.loc = pCurLoc 
    end update
    on die me
      pMe.scriptInstanceList = []  -- must manually clear this property
      pMe.puppet = false
    end
    We setup everything in a Movie script:
    -- Movie Script
    global gBulletCntrl
    on prepareMovie
      gBulletCntrl = script("Bullet Control").new()
      the mouseDownScript = "gBulletCntrl.fire()"  -- route mouseDown events to the global object gBulletCntrl.
    end prepareMovie
    on stopMovie
      the mouseDownScript = ""
    end stopMovie
    Finally since we are shooting at other sprites we need a script on them to interact with the bullets.
    --  Hitable Sprite Behavior
    property  pMe
    on beginSprite me
      pMe = sprite(me.spriteNum)
    end beginSprite
    on enterFrame me
      -- movie sprite
    end enterFrame
    on areHitable me, HitList
      HitList.add(pMe)
    end areHitable
    on explode me
      put "Boom"
    end explode

  • Count Collisions Problem in Shooting Game

    Hi,  I am working a simple game in which a ship fires at approaching asteroids and I am having problems with the collision between the ship and the
    asteroid. In the ship movieClipI have made it glow red from frame 6 to signify the first 3 collisions and loss of life and then then for the fourth collision I
    have made a alpha tween from frame 87 inside the ship so that it disappears to signify end of game. I have used a counter as shown below but all the ship
    does is glow so never gets to frame 87. Thanks for taking time to view this.
    //import some important flash libraries.
    import flash.events.KeyboardEvent;
    import flash.events.Event;
    import flash.display.MovieClip;
    import flash.display.Sprite;
    var countCollisions:Number =0 ;
    var astArray:Array = new Array();
    var speed:Number = 10;
    //initializes variables.
    var key_left:Boolean = false;
    var key_right:Boolean = false;
    var key_up:Boolean = false;
    var key_down:Boolean = false;
    var key_space:Boolean = false;
    var shootLimiter:Number=0;
    //Checks if the player presses a key.
    var timer:Timer = new Timer(2000, 10);
    timer.addEventListener(TimerEvent.TIMER, AddAsteroid);
    timer.start();
    stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
    stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
    var ship:MovieClip = new Ship()
    var backgr:MovieClip = new Background();
    backgr.x = 0;
    backgr.y = 45;
    addChild(backgr);
    addChild(ship);
    function AddAsteroid(e:TimerEvent):void
    var asteroid:MovieClip = new Asteroid();   
    asteroid.x = 800;
    asteroid.y = Math.round(Math.random()*700);
    astArray.push(asteroid);  
    addChild(asteroid);
    asteroid.addEventListener(Event.ENTER_FRAME,asteroidmove);   
    function asteroidmove(e:Event):void
    asteroid.x--
    for(var i=0; i<astArray.length; i++)
      if(astArray[i].hitTestObject(ship))
      countCollisions++;
      ship.gotoAndPlay(6);
       if(countCollisions ==4)
       ship.gotoAndPlay(87);
      if(astArray[i].stage)
            removeChild(astArray[i]);
            removeEventListener(Event.ENTER_FRAME,asteroidmove);
    addEventListener(Event.ENTER_FRAME,backgroundmove);
    function backgroundmove(e:Event):void
    backgr.x -= 1;
    if(backgr.x < -2110)
    backgr.x = 0;
    //Lets the function main play every frame.
    addEventListener(Event.ENTER_FRAME,Main);
    //create the function main.
    function Main(event:Event){
    CheckKeys();
    //create the function KeyDown.
    function KeyDown(event:KeyboardEvent){
    if(event.keyCode == 37){  //checks if left arrowkey is pressed.
      key_left = true;
    if(event.keyCode == 39){  //checks if right arrowkey is pressed.
      key_right = true;
    if(event.keyCode == 38){  //checks if up arrowkey is pressed.
      key_up = true;
    if(event.keyCode == 40){  //checks if down arrowkey is pressed.
      key_down = true;
    if(event.keyCode == 32){  //checks if down arrowkey is pressed.
      key_space = true;
    function KeyUp(event:KeyboardEvent){
    if(event.keyCode == 37){  //checks if left arrowkey is released.
      key_left = false;
    if(event.keyCode == 39){  //checks if right arrowkey is released.
      key_right = false;
    if(event.keyCode == 38){  //checks if up arrowkey is released.
      key_up = false;
    if(event.keyCode == 40){  //checks if down arrowkey is released.
      key_down = false;
    if(event.keyCode == 32){  //checks if down arrowkey is released.
      key_space = false;
    function CheckKeys()
    shootLimiter += 1;
    if(key_left)
      setDirection(1);
      ship.x -= 5;
    if(key_right)
      setDirection(0);
      ship.x += 5;
    if(key_up){
      ship.y -= 5;
    if(key_down){
      ship.y += 5;
    if((key_space) && (shootLimiter > 8))
    shootLimiter = 0;
    var b = new Bullet();
    addChild(b);
    b.x = ship.x + 50;
    b.y = ship.y + 3;
    addEventListener(Event.ENTER_FRAME,moveBullet);
    function moveBullet(e:Event):void
    b.x +=10;
      if(b.x > 600)
       if(contains(b))
       removeChild(b);
              removeEventListener(Event.ENTER_FRAME,moveBullet);
    for(var i=0; i<astArray.length; i++)
      if(astArray[i].hitTestObject(b))
      removeChild(b);
      removeChild(astArray[i]);
      removeEventListener(Event.ENTER_FRAME,moveBullet);
    function setDirection(param) {
    if (param == 0) {
      ship.scaleX = 1;
    } else {
      ship.scaleX = -1;

    Thanks for your comments. I have amended the code but get the following error and the ship goes to frame 87 on the second collision.
    Can you tell me if I am on the right lines ?
    The supplied DisplayObject must be a child of the caller.
    at flash.display::DisplayObjectContainer/removeChild()
    at Function/<anonymous>()
    for(var i=0; i<astArray.length; i++)
      if(astArray[i].hitTestObject(ship))
      countCollisions++;
      removeChild(astArray[i]);
       if(countCollisions >= 4)
       ship.gotoAndPlay(87);
       removeEventListener(Event.ENTER_FRAME,asteroidmove);
       else
       ship.gotoAndPlay(6);
      //if(astArray[i].stage)
            //removeChild(astArray[i]);
      //MovieClip(astArray[i]).removeEventListener(Event.ENTER_FRAME, asteroidmove);
            //removeEventListener(Event.ENTER_FRAME,asteroidmove);

  • 3D movement and collision queries

    I have a 3D box that I want to move a camera around the
    inside of, using mousedown on sprites. I want the camera to pan
    left/right, pan up/down, and move in/out (to replicate a zoom).
    I have a bit of script where I set up the 3D environment, and
    below is the code that I have attached to the 3D member, which is
    triggered by a left button clicks on each sprite. I've mixed the
    lingo together from different bits of scripts. The camera pans
    left/right/up/down, but it doesn't 'dolly' in/out. Can someone show
    me where I'm going wrong?
    property pGroupName
    property pPanAmount
    property pDollyAmount
    property pAlerted
    property pCamera
    property pCameraOriginTransform
    property pCenter
    property pInitialized
    property pMember
    property pMemberStateOK
    property pQueuedTriggeredEvents
    property pRect
    property pSprite
    property p3dMember
    property pCameraSphere
    on beginSprite(me)
    p3dMember = sprite(me.spriteNum).member
    pSprite = sprite(me.spriteNum)
    pMember = pSprite.member
    pMemberStateOK = me.isMemberStateOK()
    pCamera = pSprite.camera
    if pMemberStateOK then
    pInitialized = me.initialize()
    else
    pInitialized = FALSE
    end if
    p3dMember = sprite(me.spriteNum).member
    pCamera = pSprite.camera
    pAlerted = FALSE
    camSphereRes =
    p3dMember.newModelResource("camSphereRes",#sphere)
    camSphereRes.radius = 20
    pCameraSphere =
    p3dMember.newModel("cameraSphere",camSphereRes)
    pCamera.addChild(pCameraSphere,#preserveParent)
    p3dMember.registerForEvent(#timeMS,#controlCamera,me,2000,50,0)
    end beginSprite
    on endSprite(me)
    if pInitialized then
    pCamera.transform = pCameraOriginTransform
    end if
    end endSprite
    on enterFrame(me)
    if pMemberStateOK then
    if pInitialized then
    if pQueuedTriggeredEvents.count > 0 then
    repeat with j = 1 to pQueuedTriggeredEvents.count
    tEvent = pQueuedTriggeredEvents[j]
    case tEvent of
    #panCameraUp:
    me.panCamera(pPanAmount, 0, 0)
    #panCameraDown:
    me.panCamera(-pPanAmount, 0, 0)
    #panCameraLeft:
    me.panCamera(0,pPanAmount, 0)
    #panCameraRight:
    me.panCamera(0,-pPanAmount, 0)
    #dollyCameraIn:
    me.dollyCamera(0,0,-pDollyAmount)
    #dollyCameraOut:
    me.dollyCamera(0,0,pDollyAmount)
    end case
    end repeat
    pQueuedTriggeredEvents = []
    end if
    else
    pInitialized = me.initialize()
    end if
    else
    pMemberStateOK = me.isMemberStateOK()
    end if
    end enterFrame
    on registerEvent(me, aEvent, aTriggerSpriteNum,
    aTargetBehaviorInstance)
    if pInitialized then
    if me = aTargetBehaviorInstance then
    tHandler = [#panCameraUp: "Pan Camera Up",\
    #panCameraDown: "Pan Camera Down",\
    #panCameraLeft: "Pan Camera Left",\
    #panCameraRight: "Pan Camera Right",\
    #dollyCameraIn: "Move Camera In",\
    #dollyCameraOut: "Move Camera Out"].getOne(aEvent)
    if symbolP(tHandler) then
    pQueuedTriggeredEvents.add(tHandler)
    end if
    end if
    end if
    end registerEvent
    on withGroupNameOf(me, aName, aList)
    if aName = pGroupName then
    if voidP(aList.getAProp(me.spriteNum)) then
    tNewList = [:]
    tNewList.addProp(me.getScriptName(),me)
    aList.addProp(me.spriteNum, tNewList)
    else
    tBehaviorName = me.getScriptName()
    tSpriteBehaviorList = aList.getProp(me.spriteNum)
    if voidP(tSpriteBehaviorList.getAProp(tBehaviorName)) then
    tSpriteBehaviorList.addProp(me.getScriptName(),me)
    else
    nothing
    end if
    end if
    end if
    end withGroupNameOf
    on controlCamera me
    collisionList =
    p3dMember.modelsUnderRay(pCamera.worldPosition,\
    -pCamera.transform.xAxis,#detailed)
    if (collisionList.count) then
    me.checkForCollision(collisionList[1])
    end if
    collisionList =
    p3dMember.modelsUnderRay(pCamera.worldPosition,\
    pCamera.transform.xAxis,#detailed)
    if (collisionList.count) then
    me.checkForCollision(collisionList[1])
    end if
    collisionList =
    p3dMember.modelsUnderRay(pCamera.worldPosition,\
    -pCamera.transform.zAxis,#detailed)
    if (collisionList.count) then
    me.checkForCollision(collisionList[1])
    end if
    collisionList =
    p3dMember.modelsUnderRay(pCamera.worldPosition,\
    pCamera.transform.zAxis,#detailed)
    if (collisionList.count) then
    me.checkForCollision(collisionList[1])
    end if
    end
    on checkForCollision me, thisData
    dist = thisData.distance
    if (dist < pCameraSphere.resource.radius) then
    diff = pCameraSphere.resource.radius - dist
    tVector = thisData.isectNormal * diff
    pCamera.translate(tVector,#world)
    end if
    end
    on initialize(me)
    pCamera = pSprite.camera
    pCameraOriginTransform = duplicate(pCamera.transform)
    pRect = pSprite.rect
    pCenter = point(pRect.left + (pRect.width / 2.0), pRect.top
    + (pRect.height / 2.0))
    pQueuedTriggeredEvents = []
    return(TRUE)
    end initialize
    on isMemberStateOK(me)
    tOKstate = FALSE
    case pMember.type of
    #shockwave3d:
    if pMember.state >= 2 then
    tOKstate = TRUE
    end if
    #text:
    if pMember.displayMode = #mode3D then
    if pMember.state >= 2 then
    tOKstate = TRUE
    end if
    else
    if NOT(pAlerted) then
    me.textTypeAlert()
    pAlerted = TRUE
    end if
    end if
    end case
    return(tOKstate)
    end isMemberStateOK
    on panCamera(me, aX, aY, aZ)
    pCamera.rotate(aX, aY, aZ)
    end panCamera
    on dollyCamera(me, aDollyAmount)
    pCamera.translate(0,0, aDollyAmount)
    end dollyCamera
    on textTypeAlert(me)
    tString1 = "The behavior indicated below requires that its
    text member's display be set to 3D Mode. " & \
    "This sprite's member is not set that way. " & \
    "Please correct this." & RETURN & RETURN
    tString2= "Sprite" & ":" && string(me.spriteNum)
    & RETURN & RETURN
    tString3 = "Behavior" & ":" && QUOTE &
    me.getScriptName() & QUOTE
    alert(me.typeset(tString1 & tString2 & tString3))
    end textTypeAlert
    on isOKtoAttach(aScript, aSpriteType, aSpriteNum)
    case aSpriteType of
    #Graphic:
    case sprite(aSpriteNum).member.type of
    #shockwave3d:
    return(TRUE)
    #text:
    if sprite(aSpriteNum).member.displayMode = #mode3D then
    return(TRUE)
    end if
    end case
    #script:
    return(FALSE)
    end case
    end isOKtoAttach
    on getPropertyDescriptionList(aScript)
    if the currentSpriteNum > 0 then
    tGPDList = [:]
    if aScript.is3D(sprite(the currentSpriteNum).member) then
    tGPDList[#pPanAmount] = \
    [#comment:"Degrees to pan per frame",\
    #format: #integer,\
    #default: 2]
    tGPDList[#pDollyAmount] = \
    [#comment:"Amount to dolly per frame",\
    #format:#float,\
    #default: 5.0]
    tGPDList[#pGroupName] = \
    [#comment:"Which group does this behavior belong to?",\
    #format: #string,\
    #default: "Unassigned!" ]
    end if
    return(tGPDList)
    end if
    end getPropertyDescriptionList
    on getScriptName(me)
    tScriptName = string(me.script)
    tName = EMPTY
    repeat with tWord = 2 to tScriptName.word.count
    tName = tName && tScriptName.word[tWord]
    end repeat
    tName = tName.char[3..(tName.char.count) - 2]
    return(tName)
    end getScriptName
    on is3D(me, aMember)
    tIs3D = FALSE
    case aMember.type of
    #shockwave3d:
    tIs3D = TRUE
    #text:
    if aMember.displayMode = #mode3D then
    tIs3D = TRUE
    end if
    end case
    return(tIs3D)
    end is3D
    on typeSet(aScript, aString)
    tCharLimit = 50
    tTempChunk = aString.char[1..tCharLimit]
    tNewString = EMPTY
    repeat while tTempChunk <> EMPTY
    tTempChunk = aString.char[1..tCharLimit]
    tCount = tTempChunk.char.count
    if tTempChunk.char[tCharLimit] = " " then
    tStopWord = tTempChunk.word.count
    else if aString.char[tCharLimit + 1] = " " then
    tStopWord = tTempChunk.word.count
    else if tTempChunk.char.count < tCharLimit then
    tStopWord = tTempChunk.word.count
    else
    tStopWord = tTempChunk.word.count - 1
    end if
    tTempChunk = aString.word[1..tStopWord]
    tNewString = tNewString & RETURN & tTempChunk
    delete aString.word[1..tStopWord]
    end repeat
    return(tNewString)
    end typeSet
    --beginInterfaceBlock
    --publicHandler = [#panCameraUp: "Pan Camera Up"]
    --publicHandler = [#panCameraDown: "Pan Camera Down"]
    --publicHandler = [#panCameraLeft: "Pan Camera Left"]
    --publicHandler = [#panCameraRight: "Pan Camera Right"]
    --publicHandler = [#dollyCameraIn: "Move Camera In"]
    --publicHandler = [#dollyCameraOut: "Move Camera Out"]
    --respondsTo = [#mouse, #key]
    --respondToOnlyThisSprite = [FALSE]
    --endInterfaceBlock

    I think you may be right, and that's the slightly shorter
    version!!!!
    Thanks for the script, it works really smoothly. I'm trying
    to digest it at the moment, my animation needs to be in a 'from the
    inside looking out' rather than 'outside looing in', plus I have
    exponent buttons rather than sliders. And I have the small problem
    of collision detection that I hope I've fixed.
    Thanks very much though, hopefully this might shed some light
    on where I'm going wrong. I'll email back if (or when!) I get any
    questions on it (if that's ok with you!?!).

  • Good collision detection?

    I have been looking into quadtrees since it is a way to detect collisions. Is there another better way to do this? My game also has a system of sorting sprites in an array based on there relative locations on the map. ie: my character can appear in front of a tree or behind it. I have a complex system to do this which tests polygons however I was wondering if there is an expert way to do this.

    well my tank game has two levels of collision detection. Well, I guess in a way it handles all the items in 3 levels.
    First level, I have a Vector storing the items on the screen. They're only evaluated in any way if they're in the Vector. I refresh that vector every 10 frames by testing all the objects in the game to see if they're in a rectangle that surrounds the screen.
    After that, to check collisions I have a simple distance formula check that finds the distance between the centers of two objects (ie. bullet and tank) and compares them to the sum of the largest dimensions (width for both) to see if they're close enough to collide.
    If that check returns true, it calls a third level of collision checking. This check intersects the areas I've created from polygons that outline my objects. This way even if they're rotated in any way, the check only returns true if there's an honest to goodness real accurate collision. This check takes much longer than the previous one, but since it has the first check behind it, this check isn't called very often.

  • Collision Detections in Tilemaps

    I need some help with collision detection with tilemaps. I have the following code for the tilemap:
    import java.awt.*;
    public class TileMap {
         final int EMPTY = 0;
         final int WALL = 1;
         private static final int WIDTH = 30;
         private static final int HEIGHT = 40;
         public static final int TILE_SIZE = 15;
         private int[][] map = new int[WIDTH][HEIGHT];
         public TileMap() {
              for (int i=0;i<HEIGHT;i++) {
                   map[0] = WALL;
                   map[29][i] = WALL;     
              for (int i=0;i<WIDTH;i++) {     
                   map[i][0] = WALL;
                   map[i][39] = WALL;
         public void paint(Graphics g) {
              for (int x=0;x<WIDTH;x++) {
                   for (int y=0;y<HEIGHT;y++) {
                        if (map[x][y] == WALL) {
                             g.setColor(Color.RED);
                             g.fillRect(x*TILE_SIZE,y*TILE_SIZE,TILE_SIZE,TILE_SIZE);
    Im finding it hard to find a good tutorial on simple collision detection. Can anyone explain how i would work out some simple collision detection. For example, lets say there is one sprite, how would i figure out which tile the sprite is on? How would i detect the next sprite? Just need the concept.
    Thanks very much.
    Edited by: Java_Jenius on Jun 28, 2009 8:34 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Take a look at http://www.13thmonkey.org/~boris/jgame/ for example.
    It is an open source gaming engine and features sprites and collision detection.

  • Co-ordinates of sprites drawn from mouse appear 0.

    Sorry for the confusing title.
    I asked this question few weeks back - http://forums.adobe.com/thread/1106063?tstart=0
    Using Ned's code, I was able to add the drawn lines during runtime, to the sprites, which were being added to the array "lines"
    public class Main_Game extends MovieClip
                        private var drawing:Boolean;
                        var line_mc:Sprite;
                        public static var lines:Array = new Array();
                        public function Main_Game()
                        drawing = false;//to start with
                        stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
                        stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
                        stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
                        public function startDrawing(event:MouseEvent):void
                         line_mc = new Sprite();
                            addChild(line_mc);
                   lines.push(line_mc);
                         line_mc.graphics.lineStyle(9,0x000000);
                        //move to the correct starting position for drawing
                         line_mc.graphics.moveTo( mouseX, mouseY);
                        drawing = true;
                        public function draw(event:MouseEvent)
                        if(drawing)
                                  line_mc.graphics.lineTo(mouseX,mouseY);
                        public function stopDrawing(event:MouseEvent)
                        drawing = false;
    Now, I need these lines, to follow a collision detection. For that I need the sprites co-ordinates. When it was not working, I tried doing a trace on the sprite co-ordinates in a for-loop as lines[i].x, but it always showed 0.
    Any help with this, please?

    all your sprites are at 0,0.
    use:
    public class Main_Game extends MovieClip
                        var line_mc:Sprite;
                        public static var lines:Array = new Array();
                        public function Main_Game()
                        stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
                        stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
                        public function startDrawing(event:MouseEvent):void
          stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
                         line_mc = new Sprite();
    line_mc.x=mouseX;
    line_mc.y=mouseY;
                            addChild(line_mc);
                   lines.push(line_mc);
                         line_mc.graphics.lineStyle(9,0x000000);
                        //move to the correct starting position for drawing
                         line_mc.graphics.moveTo( 0, 0);
                        public function draw(event:MouseEvent)
                                  line_mc.graphics.lineTo(mouseX-line_mc.x,mouseY-line_mc.y);
                        public function stopDrawing(event:MouseEvent)
                             stage.removeEventListener(MouseEvent.MOUSE_MOVE, draw);

  • Using Collisions to Change Frame - Help Please

    Hello, I always come to this forum when I need help - its a
    great source of information. Was hoping someone knew what to do
    about my latest problem. I have a scene with several objects - a
    character you can move around and several token he picks up.
    Collision detection is achieved with Collision Modifiers. Upon the
    character touching one of these tokens I call a global variable
    called frame jump which is initially set to false. When I pick up a
    token it becomes true and it goes to the framejump handler which
    then tells the movie to switch frames.
    My problem is that I cant seem to set up the modifiers
    properly so that more the one frame can be viewed. Currently no
    matter what token I go to in the scene - the same frame of the
    movie comes up. I dont know what is causing it.
    My Code (apologies for what might be horrible code)

    Here's what I think you are trying to do:
    When the user's character collides with one of the token
    objects, you want to unlock a scene at a given frame. If the user
    has collected a number of tokens, all the associated scenes should
    be unlocked.
    It seems to me that the same 3D sprite containing the same 3D
    member appears at all the target frames. This leads me to guess
    that the "scenes" you wish to jump to are in fact inside the same
    3D world.
    It might be helpful if you could create a storyboard of how
    your movie is to work, and post it somewhere on-line so that we can
    take a look at it .

  • Tile Based Collision Detection

    I am following Tonypa's Tile Based Tutorials and I have to
    say, they are great. He covers everything needed, except for one
    thing I am troubled on - Refering to Tutorial 9,
    http://www.tonypa.pri.ee/tbw/tut09.html,
    Stupid Enemy, instead of an enemy I want to make this a NPC who
    walks around in a village. So what do I do to make it so that I, or
    the char, doesn't walk right over the enemy/NPC? I am trying to
    develop an RPG, and it would look silly to have the character walk
    on top of the NPC. Can someone provided a snippet on how to make a
    collision detection with the NPC and not walk on top/under the NPC?
    One last favor to ask: What if I want to talk to the NPC if I
    am within a half tile? Would anyone be willing to share info on how
    this as well?
    Thanks a bunch in advance

    Ok, let me see if I get the read correct here: you have your scenery objects as tiles and when moving your players/NPC's through the scenery you are not scrolling the background as you go, but when you get to s certain point you want to scroll the tiles of the background also, so you can have new scenery cycle in as needed an still have the tiled background objects and new tiled background objects work for collision detection.
    If my take on your project is correct, then you have to make your tiles addressed with relative addressing formulas as you'll probably need to do with your sprites also.
    So the way this will go is that you have to make an offset and add them into your formula based on your character position. Then based on your character position you can choose to scroll your tiles left, right, up, down or what ever you choose to support. As a tile falls fully off the screen, you can dispose of it or cycle back through depending on how you implement your background.

  • Trying to get collision detection working with havok

    Hi - I'm having some trouble using collision detection within
    director using a w3d file with havok applied to it. I've been using
    the registerinterest function but I get a "value out of range"
    error.
    This is my code (there is a cone and box on a plane imported
    from 3d max - named Cone01 and Box01 these are both movable rigid
    bodies).
    on beginSprite me
    box1=member("3d").model("Box01")
    cone1=member("3d").model("Cone01")
    w = member ( 1 )
    hk = member( 2 )
    hk.initialize( w, 0.1, 1 )
    hk.registerInterest (box1, cone1, 10, 0, #collision, me)
    end
    on collision me, details
    sound(2).play(member("hihats"))
    end
    on enterFrame me
    end
    I've also tried this and had no luck:
    on beginSprite me
    rb1 = sprite(1).pHavok.rigidBody("Box01")
    rb2 = sprite(1).pHavok.rigidBody("Cone01")
    w = member ( 1 )
    hk = member( 2 )
    hk.initialize( w, 0.1, 1 )
    hk.registerInterest (rb1, rb2, 10, 0, #collision, me)
    end
    Any help would be great.
    Thanks

    quote:
    Originally posted by:
    josiewales
    Hi - I'm having some trouble using collision detection within
    director using a w3d file with havok applied to it.
    Just study this example:
    http://necromanthus.com/Games/ShockWave/tutorials/FPS_Havok.html
    cheers

  • Simple collision detection - help needed

    ok, im having trouble with collision detection. i think i've
    got the first bit right (below) but i cant seem to complete the
    other behaviour which i plan on atteching to the sprite in channel
    73 to complete the collision detection.
    global gCollision
    on collisionDetect me
    if sprite(me.spriteNum).within(73) then
    go to frame "end"
    end if
    end
    thanks

    Try intersect function:
    if sprite i intersects j then put("You placed it correctly.")
    "P2Vulco" <[email protected]> wrote in
    message
    news:e2qa5r$l1i$[email protected]..
    > im trying to do this:
    >
    > when sprite 73 collides with sprite 14 then do something

Maybe you are looking for

  • How to make a Recovery Image DVD for my Satellite A200-1GB?

    Hi Experts, As I have wrote before I divided my HDD 2nd partitions in to 2partitions. Now I want to make a recovery DVD except the manufacturer provided DVD. The reason I want that is the USER MANUAL says when we are restoring by the manufacturer Pro

  • Error message on New Computer

    Does a new computer affect the ability to download books to Nook from Adobe Digital Editions.  I get an error message on the new computer of C E Copy not allowed.  No permission to copy this book.  I did not have a problem on the old computer

  • Convert Values in Rows to Columns

    Hi, i have a table with information of work handled. Example shown below. ID | Key | Value 1 | Agent | 123 2 | Start | 01/12/12 01:52 3 | End | 01/12/12 01:56 What I would like to do is the information in the Column Key to become Column Headers and t

  • Problem with destination org of requisition

    Hi everybody, I have a few trouble when i use requisition in centralized procurement. Please help me to cover it For example i have 2 ledger: Ledger A -> OU A1 -> Org A1.1, Org A1.2, Org A1.3 Ledger B -> OU B1 -> Org B1.1 Can I raise a requisition in

  • Freight, octroi not to be shown in Print preview

    Dear friends, I want freight and octroi not to be shown in print preview although i am maintaining those condition types in condition tab. Their value should not add up to the net value of material in print preview. Pl suggest how it's possible? Regd