Мой сценарий оружия работает, но пули ничего не делают

Если метод equals() присутствует в классе java.lang.Object, и ожидается, что он проверяет эквивалентность состояния объектов! Это означает, что содержимое объектов. В то время как ожидается, что оператор == проверяет, что фактические экземпляры объекта одинаковы или нет.

Пример

Рассмотрим две различные ссылочные переменные, str1 и str2:

str1 = new String("abc");
str2 = new String("abc");

Если вы используете equals()

System.out.println((str1.equals(str2))?"TRUE":"FALSE");

, вы получите выход как TRUE, если вы используете ==.

System.out.println((str1==str2) ? "TRUE" : "FALSE");

Теперь вы получите вывод FALSE в качестве вывода, потому что оба str1 и str2 указывают на два разных объекта, хотя оба они имеют одинаковое строковое содержимое. Именно из-за new String() каждый новый объект создается каждый раз.

-1
задан Wowzer12 10 March 2019 в 01:43
поделиться

1 ответ

Из того, как это звучит, вы хотите создать игру, в которой кирпичи получают урон при выстреле, но по какой-то причине они не получают урон. Вещи, которые я бы искал при отладке, это попытаться ответить на следующие вопросы:

1) Появляются ли пули, когда и где я хочу, чтобы?

2) Пули попадают в правильное направление?

3) Обнаружили ли кирпичи, что они были затронуты пулей?

Ваш пример кода дает подсказки только по вопросам 1 и 2. Одной из проблем может быть то, что ваша пуля расчет скорости посылает пулю в направлении, которое вы не ожидаете.

Попробуйте что-то вроде этого в LocalScript, чтобы убедиться, что пули созданы и перемещаются:

-- alias some variables to make it easier to find things
local fireButton = script.Parent -- <-- assumed that this is a button
local carWorkspace = script.Parent.Parent.Parent.Parent.Parent.Parent.Workspace
local car1 = carWorkspace.Car1
local machineGun = car1.Body.Weapons.MachineGun

-- create some constants for math stuff
local bulletSpeed = 30.0 -- <-- this is super slow so that we can test it
local counterGravityVect = Vector3.new(0, 93.2, 0) -- <-- this is witchcraft

-- make a helper for cloning bullets
local function createBullet(templateBullet, targetVector)
    local newBullet = templateBullet:Clone()
    newBullet.Transparency = 0
    newBullet.Anchored = false
    newBullet.Parent = game.Workspace

    -- use a BodyForce instead of Velocity to propel the bullet
    -- NOTE - there's no clear documentation about how much force you need
    --        just mess with bulletSpeed until it moves fast enough for you
    newBullet.Massless = true
    local targetForce = BodyForce.new()
    targetForce.Force = counterGravityVect + (targetVector * bulletSpeed)
    targetForce.Parent = newBullet

    return newBullet
end 

function fireGun()
    print("Gun fired, creating bullets...)

    -- play the bang sounds
    machineGun.Part1.Sound:Play()
    machineGun.Part2.Sound:Play()

    -- get the orientation of the machine gun
    local targetVect = machineGun.CFrame.LookVector

    -- spawn two new bullets and fire them
    -- in the same direction as the machine gun
    local b1 = createBullet(machineGun.bullet1, targetVect)
    local b2 = createBullet(machineGun.bullet2, targetVect)
end

-- listen for mouse or touch input to the
fireButton.Activated:Connect(fireGun)

Но вам также нужно убедиться, что ваши кирпичи получают урон при попадании. Вот простой способ сделать это:

1) Создать деталь

2) Добавить NumberValue как дочерний элемент

3) Добавить скрипт в деталь, которая выглядит как это:

print("Hello world!- wall")
local wall = script.Parent
local health = wall.Health
local maxHealth = 10

-- top off the health
health.Value = maxHealth

-- add an event listener to the wall to make sure that it can get shot
wall.Touched:Connect(function(toucher)
    print("Wall Touched ", toucher)
    if (toucher.Name == "bullet") then
        print("Got shot, losing health : ", health.Value - 1)
        health.Value = health.Value - 1
        toucher:Destroy()

        if health.Value <= 0 then
            wall:Destroy()
        end
    end
end)

Я надеюсь, что это несколько охватило основы того, что может пойти не так. Дайте мне знать, если что-то из этого не имеет смысла. Удачи!

0
ответ дан Kylaaa 10 March 2019 в 01:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: